alloc/collections/btree/map.rs
1use core::borrow::Borrow;
2use core::cmp::Ordering;
3use core::error::Error;
4use core::fmt::{self, Debug};
5use core::hash::{Hash, Hasher};
6use core::iter::{FusedIterator, TrustedLen};
7use core::marker::PhantomData;
8use core::mem::{self, ManuallyDrop};
9use core::ops::{Bound, Index, RangeBounds};
10use core::ptr;
11
12use super::borrow::DormantMutRef;
13use super::dedup_sorted_iter::DedupSortedIter;
14use super::navigate::{LazyLeafRange, LeafRange};
15use super::node::ForceResult::*;
16use super::node::{self, Handle, NodeRef, Root, marker};
17use super::search::SearchBound;
18use super::search::SearchResult::*;
19use super::set_val::SetValZST;
20use crate::alloc::{Allocator, Global};
21use crate::vec::Vec;
22
23mod entry;
24
25use Entry::*;
26#[stable(feature = "rust1", since = "1.0.0")]
27pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
28
29/// Minimum number of elements in a node that is not a root.
30/// We might temporarily have fewer elements during methods.
31pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
32
33// A tree in a `BTreeMap` is a tree in the `node` module with additional invariants:
34// - Keys must appear in ascending order (according to the key's type).
35// - Every non-leaf node contains at least 1 element (has at least 2 children).
36// - Every non-root node contains at least MIN_LEN elements.
37//
38// An empty map is represented either by the absence of a root node or by a
39// root node that is an empty leaf.
40
41/// An ordered map based on a [B-Tree].
42///
43/// Given a key type with a [total order], an ordered map stores its entries in key order.
44/// That means that keys must be of a type that implements the [`Ord`] trait,
45/// such that two keys can always be compared to determine their [`Ordering`].
46/// Examples of keys with a total order are strings with lexicographical order,
47/// and numbers with their natural order.
48///
49/// Iterators obtained from functions such as [`BTreeMap::iter`], [`BTreeMap::into_iter`], [`BTreeMap::values`], or
50/// [`BTreeMap::keys`] produce their items in key order, and take worst-case logarithmic and
51/// amortized constant time per item returned.
52///
53/// It is a logic error for a key to be modified in such a way that the key's ordering relative to
54/// any other key, as determined by the [`Ord`] trait, changes while it is in the map. This is
55/// normally only possible through [`Cell`], [`RefCell`], global state, I/O, or unsafe code.
56/// The behavior resulting from such a logic error is not specified, but will be encapsulated to the
57/// `BTreeMap` that observed the logic error and not result in undefined behavior. This could
58/// include panics, incorrect results, aborts, memory leaks, and non-termination.
59///
60/// # Examples
61///
62/// ```
63/// use std::collections::BTreeMap;
64///
65/// // type inference lets us omit an explicit type signature (which
66/// // would be `BTreeMap<&str, &str>` in this example).
67/// let mut movie_reviews = BTreeMap::new();
68///
69/// // review some movies.
70/// movie_reviews.insert("Office Space", "Deals with real issues in the workplace.");
71/// movie_reviews.insert("Pulp Fiction", "Masterpiece.");
72/// movie_reviews.insert("The Godfather", "Very enjoyable.");
73/// movie_reviews.insert("The Blues Brothers", "Eye lyked it a lot.");
74///
75/// // check for a specific one.
76/// if !movie_reviews.contains_key("Les Misérables") {
77/// println!("We've got {} reviews, but Les Misérables ain't one.",
78/// movie_reviews.len());
79/// }
80///
81/// // oops, this review has a lot of spelling mistakes, let's delete it.
82/// movie_reviews.remove("The Blues Brothers");
83///
84/// // look up the values associated with some keys.
85/// let to_find = ["Up!", "Office Space"];
86/// for movie in &to_find {
87/// match movie_reviews.get(movie) {
88/// Some(review) => println!("{movie}: {review}"),
89/// None => println!("{movie} is unreviewed.")
90/// }
91/// }
92///
93/// // Look up the value for a key (will panic if the key is not found).
94/// println!("Movie review: {}", movie_reviews["Office Space"]);
95///
96/// // iterate over everything.
97/// for (movie, review) in &movie_reviews {
98/// println!("{movie}: \"{review}\"");
99/// }
100/// ```
101///
102/// A `BTreeMap` with a known list of items can be initialized from an array:
103///
104/// ```
105/// use std::collections::BTreeMap;
106///
107/// let solar_distance = BTreeMap::from([
108/// ("Mercury", 0.4),
109/// ("Venus", 0.7),
110/// ("Earth", 1.0),
111/// ("Mars", 1.5),
112/// ]);
113/// ```
114///
115/// ## `Entry` API
116///
117/// `BTreeMap` implements an [`Entry API`], which allows for complex
118/// methods of getting, setting, updating and removing keys and their values:
119///
120/// [`Entry API`]: BTreeMap::entry
121///
122/// ```
123/// use std::collections::BTreeMap;
124///
125/// // type inference lets us omit an explicit type signature (which
126/// // would be `BTreeMap<&str, u8>` in this example).
127/// let mut player_stats = BTreeMap::new();
128///
129/// fn random_stat_buff() -> u8 {
130/// // could actually return some random value here - let's just return
131/// // some fixed value for now
132/// 42
133/// }
134///
135/// // insert a key only if it doesn't already exist
136/// player_stats.entry("health").or_insert(100);
137///
138/// // insert a key using a function that provides a new value only if it
139/// // doesn't already exist
140/// player_stats.entry("defence").or_insert_with(random_stat_buff);
141///
142/// // update a key, guarding against the key possibly not being set
143/// let stat = player_stats.entry("attack").or_insert(100);
144/// *stat += random_stat_buff();
145///
146/// // modify an entry before an insert with in-place mutation
147/// player_stats.entry("mana").and_modify(|mana| *mana += 200).or_insert(100);
148/// ```
149///
150/// # Background
151///
152/// A B-tree is (like) a [binary search tree], but adapted to the natural granularity that modern
153/// machines like to consume data at. This means that each node contains an entire array of elements,
154/// instead of just a single element.
155///
156/// B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing
157/// the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal
158/// choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum number of
159/// comparisons necessary to find an element (log<sub>2</sub>n). However, in practice the way this
160/// is done is *very* inefficient for modern computer architectures. In particular, every element
161/// is stored in its own individually heap-allocated node. This means that every single insertion
162/// triggers a heap-allocation, and every comparison is a potential cache-miss due to the indirection.
163/// Since both heap-allocations and cache-misses are notably expensive in practice, we are forced to,
164/// at the very least, reconsider the BST strategy.
165///
166/// A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing
167/// this, we reduce the number of allocations by a factor of B, and improve cache efficiency in
168/// searches. However, this does mean that searches will have to do *more* comparisons on average.
169/// The precise number of comparisons depends on the node search strategy used. For optimal cache
170/// efficiency, one could search the nodes linearly. For optimal comparisons, one could search
171/// the node using binary search. As a compromise, one could also perform a linear search
172/// that initially only checks every i<sup>th</sup> element for some choice of i.
173///
174/// Currently, our implementation simply performs naive linear search. This provides excellent
175/// performance on *small* nodes of elements which are cheap to compare. However in the future we
176/// would like to further explore choosing the optimal search strategy based on the choice of B,
177/// and possibly other factors. Using linear search, searching for a random element is expected
178/// to take B * log(n) comparisons, which is generally worse than a BST. In practice,
179/// however, performance is excellent.
180///
181/// [B-Tree]: https://en.wikipedia.org/wiki/B-tree
182/// [binary search tree]: https://en.wikipedia.org/wiki/Binary_search_tree
183/// [total order]: https://en.wikipedia.org/wiki/Total_order
184/// [`Cell`]: core::cell::Cell
185/// [`RefCell`]: core::cell::RefCell
186#[stable(feature = "rust1", since = "1.0.0")]
187#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeMap")]
188#[rustc_insignificant_dtor]
189pub struct BTreeMap<
190 K,
191 V,
192 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
193> {
194 root: Option<Root<K, V>>,
195 length: usize,
196 /// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes).
197 // Although some of the accessory types store a copy of the allocator, the nodes do not.
198 // Because allocations will remain live as long as any copy (like this one) of the allocator
199 // is live, it's unnecessary to store the allocator in each node.
200 pub(super) alloc: ManuallyDrop<A>,
201 // For dropck; the `Box` avoids making the `Unpin` impl more strict than before
202 _marker: PhantomData<crate::boxed::Box<(K, V), A>>,
203}
204
205#[stable(feature = "btree_drop", since = "1.7.0")]
206unsafe impl<#[may_dangle] K, #[may_dangle] V, A: Allocator + Clone> Drop for BTreeMap<K, V, A> {
207 fn drop(&mut self) {
208 drop(unsafe { ptr::read(self) }.into_iter())
209 }
210}
211
212// FIXME: This implementation is "wrong", but changing it would be a breaking change.
213// (The bounds of the automatic `UnwindSafe` implementation have been like this since Rust 1.50.)
214// Maybe we can fix it nonetheless with a crater run, or if the `UnwindSafe`
215// traits are deprecated, or disarmed (no longer causing hard errors) in the future.
216#[stable(feature = "btree_unwindsafe", since = "1.64.0")]
217impl<K, V, A: Allocator + Clone> core::panic::UnwindSafe for BTreeMap<K, V, A>
218where
219 A: core::panic::UnwindSafe,
220 K: core::panic::RefUnwindSafe,
221 V: core::panic::RefUnwindSafe,
222{
223}
224
225#[stable(feature = "rust1", since = "1.0.0")]
226impl<K: Clone, V: Clone, A: Allocator + Clone> Clone for BTreeMap<K, V, A> {
227 fn clone(&self) -> BTreeMap<K, V, A> {
228 fn clone_subtree<'a, K: Clone, V: Clone, A: Allocator + Clone>(
229 node: NodeRef<marker::Immut<'a>, K, V, marker::LeafOrInternal>,
230 alloc: A,
231 ) -> BTreeMap<K, V, A>
232 where
233 K: 'a,
234 V: 'a,
235 {
236 match node.force() {
237 Leaf(leaf) => {
238 let mut out_tree = BTreeMap {
239 root: Some(Root::new(alloc.clone())),
240 length: 0,
241 alloc: ManuallyDrop::new(alloc),
242 _marker: PhantomData,
243 };
244
245 {
246 let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped
247 let mut out_node = match root.borrow_mut().force() {
248 Leaf(leaf) => leaf,
249 Internal(_) => unreachable!(),
250 };
251
252 let mut in_edge = leaf.first_edge();
253 while let Ok(kv) = in_edge.right_kv() {
254 let (k, v) = kv.into_kv();
255 in_edge = kv.right_edge();
256
257 out_node.push(k.clone(), v.clone());
258 out_tree.length += 1;
259 }
260 }
261
262 out_tree
263 }
264 Internal(internal) => {
265 let mut out_tree =
266 clone_subtree(internal.first_edge().descend(), alloc.clone());
267
268 {
269 let out_root = out_tree.root.as_mut().unwrap();
270 let mut out_node = out_root.push_internal_level(alloc.clone());
271 let mut in_edge = internal.first_edge();
272 while let Ok(kv) = in_edge.right_kv() {
273 let (k, v) = kv.into_kv();
274 in_edge = kv.right_edge();
275
276 let k = (*k).clone();
277 let v = (*v).clone();
278 let subtree = clone_subtree(in_edge.descend(), alloc.clone());
279
280 // We can't destructure subtree directly
281 // because BTreeMap implements Drop
282 let (subroot, sublength) = unsafe {
283 let subtree = ManuallyDrop::new(subtree);
284 let root = ptr::read(&subtree.root);
285 let length = subtree.length;
286 (root, length)
287 };
288
289 out_node.push(
290 k,
291 v,
292 subroot.unwrap_or_else(|| Root::new(alloc.clone())),
293 );
294 out_tree.length += 1 + sublength;
295 }
296 }
297
298 out_tree
299 }
300 }
301 }
302
303 if self.is_empty() {
304 BTreeMap::new_in((*self.alloc).clone())
305 } else {
306 clone_subtree(self.root.as_ref().unwrap().reborrow(), (*self.alloc).clone()) // unwrap succeeds because not empty
307 }
308 }
309}
310
311// Internal functionality for `BTreeSet`.
312impl<K, A: Allocator + Clone> BTreeMap<K, SetValZST, A> {
313 pub(super) fn replace(&mut self, key: K) -> Option<K>
314 where
315 K: Ord,
316 {
317 let (map, dormant_map) = DormantMutRef::new(self);
318 let root_node =
319 map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
320 match root_node.search_tree::<K>(&key) {
321 Found(mut kv) => Some(mem::replace(kv.key_mut(), key)),
322 GoDown(handle) => {
323 VacantEntry {
324 key,
325 handle: Some(handle),
326 dormant_map,
327 alloc: (*map.alloc).clone(),
328 _marker: PhantomData,
329 }
330 .insert(SetValZST);
331 None
332 }
333 }
334 }
335
336 pub(super) fn get_or_insert_with<Q: ?Sized, F>(&mut self, q: &Q, f: F) -> &K
337 where
338 K: Borrow<Q> + Ord,
339 Q: Ord,
340 F: FnOnce(&Q) -> K,
341 {
342 let (map, dormant_map) = DormantMutRef::new(self);
343 let root_node =
344 map.root.get_or_insert_with(|| Root::new((*map.alloc).clone())).borrow_mut();
345 match root_node.search_tree(q) {
346 Found(handle) => handle.into_kv_mut().0,
347 GoDown(handle) => {
348 let key = f(q);
349 assert!(*key.borrow() == *q, "new value is not equal");
350 VacantEntry {
351 key,
352 handle: Some(handle),
353 dormant_map,
354 alloc: (*map.alloc).clone(),
355 _marker: PhantomData,
356 }
357 .insert_entry(SetValZST)
358 .into_key()
359 }
360 }
361 }
362}
363
364/// An iterator over the entries of a `BTreeMap`.
365///
366/// This `struct` is created by the [`iter`] method on [`BTreeMap`]. See its
367/// documentation for more.
368///
369/// [`iter`]: BTreeMap::iter
370#[must_use = "iterators are lazy and do nothing unless consumed"]
371#[stable(feature = "rust1", since = "1.0.0")]
372pub struct Iter<'a, K: 'a, V: 'a> {
373 range: LazyLeafRange<marker::Immut<'a>, K, V>,
374 length: usize,
375}
376
377#[stable(feature = "collection_debug", since = "1.17.0")]
378impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Iter<'_, K, V> {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 f.debug_list().entries(self.clone()).finish()
381 }
382}
383
384#[stable(feature = "default_iters", since = "1.70.0")]
385impl<'a, K: 'a, V: 'a> Default for Iter<'a, K, V> {
386 /// Creates an empty `btree_map::Iter`.
387 ///
388 /// ```
389 /// # use std::collections::btree_map;
390 /// let iter: btree_map::Iter<'_, u8, u8> = Default::default();
391 /// assert_eq!(iter.len(), 0);
392 /// ```
393 fn default() -> Self {
394 Iter { range: Default::default(), length: 0 }
395 }
396}
397
398/// A mutable iterator over the entries of a `BTreeMap`.
399///
400/// This `struct` is created by the [`iter_mut`] method on [`BTreeMap`]. See its
401/// documentation for more.
402///
403/// [`iter_mut`]: BTreeMap::iter_mut
404#[must_use = "iterators are lazy and do nothing unless consumed"]
405#[stable(feature = "rust1", since = "1.0.0")]
406pub struct IterMut<'a, K: 'a, V: 'a> {
407 range: LazyLeafRange<marker::ValMut<'a>, K, V>,
408 length: usize,
409
410 // Be invariant in `K` and `V`
411 _marker: PhantomData<&'a mut (K, V)>,
412}
413
414#[stable(feature = "collection_debug", since = "1.17.0")]
415impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for IterMut<'_, K, V> {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 let range = Iter { range: self.range.reborrow(), length: self.length };
418 f.debug_list().entries(range).finish()
419 }
420}
421
422#[stable(feature = "default_iters", since = "1.70.0")]
423impl<'a, K: 'a, V: 'a> Default for IterMut<'a, K, V> {
424 /// Creates an empty `btree_map::IterMut`.
425 ///
426 /// ```
427 /// # use std::collections::btree_map;
428 /// let iter: btree_map::IterMut<'_, u8, u8> = Default::default();
429 /// assert_eq!(iter.len(), 0);
430 /// ```
431 fn default() -> Self {
432 IterMut { range: Default::default(), length: 0, _marker: PhantomData {} }
433 }
434}
435
436/// An owning iterator over the entries of a `BTreeMap`, sorted by key.
437///
438/// This `struct` is created by the [`into_iter`] method on [`BTreeMap`]
439/// (provided by the [`IntoIterator`] trait). See its documentation for more.
440///
441/// [`into_iter`]: IntoIterator::into_iter
442#[stable(feature = "rust1", since = "1.0.0")]
443#[rustc_insignificant_dtor]
444pub struct IntoIter<
445 K,
446 V,
447 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
448> {
449 range: LazyLeafRange<marker::Dying, K, V>,
450 length: usize,
451 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
452 alloc: A,
453}
454
455impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
456 /// Returns an iterator of references over the remaining items.
457 #[inline]
458 pub(super) fn iter(&self) -> Iter<'_, K, V> {
459 Iter { range: self.range.reborrow(), length: self.length }
460 }
461}
462
463#[stable(feature = "collection_debug", since = "1.17.0")]
464impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for IntoIter<K, V, A> {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 f.debug_list().entries(self.iter()).finish()
467 }
468}
469
470#[stable(feature = "default_iters", since = "1.70.0")]
471impl<K, V, A> Default for IntoIter<K, V, A>
472where
473 A: Allocator + Default + Clone,
474{
475 /// Creates an empty `btree_map::IntoIter`.
476 ///
477 /// ```
478 /// # use std::collections::btree_map;
479 /// let iter: btree_map::IntoIter<u8, u8> = Default::default();
480 /// assert_eq!(iter.len(), 0);
481 /// ```
482 fn default() -> Self {
483 IntoIter { range: Default::default(), length: 0, alloc: Default::default() }
484 }
485}
486
487/// An iterator over the keys of a `BTreeMap`.
488///
489/// This `struct` is created by the [`keys`] method on [`BTreeMap`]. See its
490/// documentation for more.
491///
492/// [`keys`]: BTreeMap::keys
493#[must_use = "iterators are lazy and do nothing unless consumed"]
494#[stable(feature = "rust1", since = "1.0.0")]
495pub struct Keys<'a, K, V> {
496 inner: Iter<'a, K, V>,
497}
498
499#[stable(feature = "collection_debug", since = "1.17.0")]
500impl<K: fmt::Debug, V> fmt::Debug for Keys<'_, K, V> {
501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 f.debug_list().entries(self.clone()).finish()
503 }
504}
505
506/// An iterator over the values of a `BTreeMap`.
507///
508/// This `struct` is created by the [`values`] method on [`BTreeMap`]. See its
509/// documentation for more.
510///
511/// [`values`]: BTreeMap::values
512#[must_use = "iterators are lazy and do nothing unless consumed"]
513#[stable(feature = "rust1", since = "1.0.0")]
514pub struct Values<'a, K, V> {
515 inner: Iter<'a, K, V>,
516}
517
518#[stable(feature = "collection_debug", since = "1.17.0")]
519impl<K, V: fmt::Debug> fmt::Debug for Values<'_, K, V> {
520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521 f.debug_list().entries(self.clone()).finish()
522 }
523}
524
525/// A mutable iterator over the values of a `BTreeMap`.
526///
527/// This `struct` is created by the [`values_mut`] method on [`BTreeMap`]. See its
528/// documentation for more.
529///
530/// [`values_mut`]: BTreeMap::values_mut
531#[must_use = "iterators are lazy and do nothing unless consumed"]
532#[stable(feature = "map_values_mut", since = "1.10.0")]
533pub struct ValuesMut<'a, K, V> {
534 inner: IterMut<'a, K, V>,
535}
536
537#[stable(feature = "map_values_mut", since = "1.10.0")]
538impl<K, V: fmt::Debug> fmt::Debug for ValuesMut<'_, K, V> {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
541 }
542}
543
544/// An owning iterator over the keys of a `BTreeMap`.
545///
546/// This `struct` is created by the [`into_keys`] method on [`BTreeMap`].
547/// See its documentation for more.
548///
549/// [`into_keys`]: BTreeMap::into_keys
550#[must_use = "iterators are lazy and do nothing unless consumed"]
551#[stable(feature = "map_into_keys_values", since = "1.54.0")]
552pub struct IntoKeys<
553 K,
554 V,
555 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
556> {
557 inner: IntoIter<K, V, A>,
558}
559
560#[stable(feature = "map_into_keys_values", since = "1.54.0")]
561impl<K: fmt::Debug, V, A: Allocator + Clone> fmt::Debug for IntoKeys<K, V, A> {
562 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563 f.debug_list().entries(self.inner.iter().map(|(key, _)| key)).finish()
564 }
565}
566
567/// An owning iterator over the values of a `BTreeMap`.
568///
569/// This `struct` is created by the [`into_values`] method on [`BTreeMap`].
570/// See its documentation for more.
571///
572/// [`into_values`]: BTreeMap::into_values
573#[must_use = "iterators are lazy and do nothing unless consumed"]
574#[stable(feature = "map_into_keys_values", since = "1.54.0")]
575pub struct IntoValues<
576 K,
577 V,
578 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
579> {
580 inner: IntoIter<K, V, A>,
581}
582
583#[stable(feature = "map_into_keys_values", since = "1.54.0")]
584impl<K, V: fmt::Debug, A: Allocator + Clone> fmt::Debug for IntoValues<K, V, A> {
585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586 f.debug_list().entries(self.inner.iter().map(|(_, val)| val)).finish()
587 }
588}
589
590/// An iterator over a sub-range of entries in a `BTreeMap`.
591///
592/// This `struct` is created by the [`range`] method on [`BTreeMap`]. See its
593/// documentation for more.
594///
595/// [`range`]: BTreeMap::range
596#[must_use = "iterators are lazy and do nothing unless consumed"]
597#[stable(feature = "btree_range", since = "1.17.0")]
598pub struct Range<'a, K: 'a, V: 'a> {
599 inner: LeafRange<marker::Immut<'a>, K, V>,
600}
601
602#[stable(feature = "collection_debug", since = "1.17.0")]
603impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for Range<'_, K, V> {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 f.debug_list().entries(self.clone()).finish()
606 }
607}
608
609/// A mutable iterator over a sub-range of entries in a `BTreeMap`.
610///
611/// This `struct` is created by the [`range_mut`] method on [`BTreeMap`]. See its
612/// documentation for more.
613///
614/// [`range_mut`]: BTreeMap::range_mut
615#[must_use = "iterators are lazy and do nothing unless consumed"]
616#[stable(feature = "btree_range", since = "1.17.0")]
617pub struct RangeMut<'a, K: 'a, V: 'a> {
618 inner: LeafRange<marker::ValMut<'a>, K, V>,
619
620 // Be invariant in `K` and `V`
621 _marker: PhantomData<&'a mut (K, V)>,
622}
623
624#[stable(feature = "collection_debug", since = "1.17.0")]
625impl<K: fmt::Debug, V: fmt::Debug> fmt::Debug for RangeMut<'_, K, V> {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 let range = Range { inner: self.inner.reborrow() };
628 f.debug_list().entries(range).finish()
629 }
630}
631
632impl<K, V> BTreeMap<K, V> {
633 /// Makes a new, empty `BTreeMap`.
634 ///
635 /// Does not allocate anything on its own.
636 ///
637 /// # Examples
638 ///
639 /// ```
640 /// use std::collections::BTreeMap;
641 ///
642 /// let mut map = BTreeMap::new();
643 ///
644 /// // entries can now be inserted into the empty map
645 /// map.insert(1, "a");
646 /// ```
647 #[stable(feature = "rust1", since = "1.0.0")]
648 #[rustc_const_stable(feature = "const_btree_new", since = "1.66.0")]
649 #[inline]
650 #[must_use]
651 pub const fn new() -> BTreeMap<K, V> {
652 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(Global), _marker: PhantomData }
653 }
654}
655
656impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
657 /// Clears the map, removing all elements.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// use std::collections::BTreeMap;
663 ///
664 /// let mut a = BTreeMap::new();
665 /// a.insert(1, "a");
666 /// a.clear();
667 /// assert!(a.is_empty());
668 /// ```
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn clear(&mut self) {
671 // avoid moving the allocator
672 drop(BTreeMap {
673 root: mem::replace(&mut self.root, None),
674 length: mem::replace(&mut self.length, 0),
675 alloc: self.alloc.clone(),
676 _marker: PhantomData,
677 });
678 }
679
680 /// Makes a new empty BTreeMap with a reasonable choice for B.
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// # #![feature(allocator_api)]
686 /// # #![feature(btreemap_alloc)]
687 /// use std::collections::BTreeMap;
688 /// use std::alloc::Global;
689 ///
690 /// let mut map = BTreeMap::new_in(Global);
691 ///
692 /// // entries can now be inserted into the empty map
693 /// map.insert(1, "a");
694 /// ```
695 #[unstable(feature = "btreemap_alloc", issue = "32838")]
696 #[must_use]
697 pub const fn new_in(alloc: A) -> BTreeMap<K, V, A> {
698 BTreeMap { root: None, length: 0, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
699 }
700}
701
702impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
703 /// Returns a reference to the value corresponding to the key.
704 ///
705 /// The key may be any borrowed form of the map's key type, but the ordering
706 /// on the borrowed form *must* match the ordering on the key type.
707 ///
708 /// # Examples
709 ///
710 /// ```
711 /// use std::collections::BTreeMap;
712 ///
713 /// let mut map = BTreeMap::new();
714 /// map.insert(1, "a");
715 /// assert_eq!(map.get(&1), Some(&"a"));
716 /// assert_eq!(map.get(&2), None);
717 /// ```
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
720 where
721 K: Borrow<Q> + Ord,
722 Q: Ord,
723 {
724 let root_node = self.root.as_ref()?.reborrow();
725 match root_node.search_tree(key) {
726 Found(handle) => Some(handle.into_kv().1),
727 GoDown(_) => None,
728 }
729 }
730
731 /// Returns the key-value pair corresponding to the supplied key. This is
732 /// potentially useful:
733 /// - for key types where non-identical keys can be considered equal;
734 /// - for getting the `&K` stored key value from a borrowed `&Q` lookup key; or
735 /// - for getting a reference to a key with the same lifetime as the collection.
736 ///
737 /// The supplied key may be any borrowed form of the map's key type, but the ordering
738 /// on the borrowed form *must* match the ordering on the key type.
739 ///
740 /// # Examples
741 ///
742 /// ```
743 /// use std::cmp::Ordering;
744 /// use std::collections::BTreeMap;
745 ///
746 /// #[derive(Clone, Copy, Debug)]
747 /// struct S {
748 /// id: u32,
749 /// # #[allow(unused)] // prevents a "field `name` is never read" error
750 /// name: &'static str, // ignored by equality and ordering operations
751 /// }
752 ///
753 /// impl PartialEq for S {
754 /// fn eq(&self, other: &S) -> bool {
755 /// self.id == other.id
756 /// }
757 /// }
758 ///
759 /// impl Eq for S {}
760 ///
761 /// impl PartialOrd for S {
762 /// fn partial_cmp(&self, other: &S) -> Option<Ordering> {
763 /// self.id.partial_cmp(&other.id)
764 /// }
765 /// }
766 ///
767 /// impl Ord for S {
768 /// fn cmp(&self, other: &S) -> Ordering {
769 /// self.id.cmp(&other.id)
770 /// }
771 /// }
772 ///
773 /// let j_a = S { id: 1, name: "Jessica" };
774 /// let j_b = S { id: 1, name: "Jess" };
775 /// let p = S { id: 2, name: "Paul" };
776 /// assert_eq!(j_a, j_b);
777 ///
778 /// let mut map = BTreeMap::new();
779 /// map.insert(j_a, "Paris");
780 /// assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
781 /// assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
782 /// assert_eq!(map.get_key_value(&p), None);
783 /// ```
784 #[stable(feature = "map_get_key_value", since = "1.40.0")]
785 pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)>
786 where
787 K: Borrow<Q> + Ord,
788 Q: Ord,
789 {
790 let root_node = self.root.as_ref()?.reborrow();
791 match root_node.search_tree(k) {
792 Found(handle) => Some(handle.into_kv()),
793 GoDown(_) => None,
794 }
795 }
796
797 /// Returns the first key-value pair in the map.
798 /// The key in this pair is the minimum key in the map.
799 ///
800 /// # Examples
801 ///
802 /// ```
803 /// use std::collections::BTreeMap;
804 ///
805 /// let mut map = BTreeMap::new();
806 /// assert_eq!(map.first_key_value(), None);
807 /// map.insert(1, "b");
808 /// map.insert(2, "a");
809 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
810 /// ```
811 #[stable(feature = "map_first_last", since = "1.66.0")]
812 pub fn first_key_value(&self) -> Option<(&K, &V)>
813 where
814 K: Ord,
815 {
816 let root_node = self.root.as_ref()?.reborrow();
817 root_node.first_leaf_edge().right_kv().ok().map(Handle::into_kv)
818 }
819
820 /// Returns the first entry in the map for in-place manipulation.
821 /// The key of this entry is the minimum key in the map.
822 ///
823 /// # Examples
824 ///
825 /// ```
826 /// use std::collections::BTreeMap;
827 ///
828 /// let mut map = BTreeMap::new();
829 /// map.insert(1, "a");
830 /// map.insert(2, "b");
831 /// if let Some(mut entry) = map.first_entry() {
832 /// if *entry.key() > 0 {
833 /// entry.insert("first");
834 /// }
835 /// }
836 /// assert_eq!(*map.get(&1).unwrap(), "first");
837 /// assert_eq!(*map.get(&2).unwrap(), "b");
838 /// ```
839 #[stable(feature = "map_first_last", since = "1.66.0")]
840 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
841 where
842 K: Ord,
843 {
844 let (map, dormant_map) = DormantMutRef::new(self);
845 let root_node = map.root.as_mut()?.borrow_mut();
846 let kv = root_node.first_leaf_edge().right_kv().ok()?;
847 Some(OccupiedEntry {
848 handle: kv.forget_node_type(),
849 dormant_map,
850 alloc: (*map.alloc).clone(),
851 _marker: PhantomData,
852 })
853 }
854
855 /// Removes and returns the first element in the map.
856 /// The key of this element is the minimum key that was in the map.
857 ///
858 /// # Examples
859 ///
860 /// Draining elements in ascending order, while keeping a usable map each iteration.
861 ///
862 /// ```
863 /// use std::collections::BTreeMap;
864 ///
865 /// let mut map = BTreeMap::new();
866 /// map.insert(1, "a");
867 /// map.insert(2, "b");
868 /// while let Some((key, _val)) = map.pop_first() {
869 /// assert!(map.iter().all(|(k, _v)| *k > key));
870 /// }
871 /// assert!(map.is_empty());
872 /// ```
873 #[stable(feature = "map_first_last", since = "1.66.0")]
874 pub fn pop_first(&mut self) -> Option<(K, V)>
875 where
876 K: Ord,
877 {
878 self.first_entry().map(|entry| entry.remove_entry())
879 }
880
881 /// Returns the last key-value pair in the map.
882 /// The key in this pair is the maximum key in the map.
883 ///
884 /// # Examples
885 ///
886 /// ```
887 /// use std::collections::BTreeMap;
888 ///
889 /// let mut map = BTreeMap::new();
890 /// map.insert(1, "b");
891 /// map.insert(2, "a");
892 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
893 /// ```
894 #[stable(feature = "map_first_last", since = "1.66.0")]
895 pub fn last_key_value(&self) -> Option<(&K, &V)>
896 where
897 K: Ord,
898 {
899 let root_node = self.root.as_ref()?.reborrow();
900 root_node.last_leaf_edge().left_kv().ok().map(Handle::into_kv)
901 }
902
903 /// Returns the last entry in the map for in-place manipulation.
904 /// The key of this entry is the maximum key in the map.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// use std::collections::BTreeMap;
910 ///
911 /// let mut map = BTreeMap::new();
912 /// map.insert(1, "a");
913 /// map.insert(2, "b");
914 /// if let Some(mut entry) = map.last_entry() {
915 /// if *entry.key() > 0 {
916 /// entry.insert("last");
917 /// }
918 /// }
919 /// assert_eq!(*map.get(&1).unwrap(), "a");
920 /// assert_eq!(*map.get(&2).unwrap(), "last");
921 /// ```
922 #[stable(feature = "map_first_last", since = "1.66.0")]
923 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, A>>
924 where
925 K: Ord,
926 {
927 let (map, dormant_map) = DormantMutRef::new(self);
928 let root_node = map.root.as_mut()?.borrow_mut();
929 let kv = root_node.last_leaf_edge().left_kv().ok()?;
930 Some(OccupiedEntry {
931 handle: kv.forget_node_type(),
932 dormant_map,
933 alloc: (*map.alloc).clone(),
934 _marker: PhantomData,
935 })
936 }
937
938 /// Removes and returns the last element in the map.
939 /// The key of this element is the maximum key that was in the map.
940 ///
941 /// # Examples
942 ///
943 /// Draining elements in descending order, while keeping a usable map each iteration.
944 ///
945 /// ```
946 /// use std::collections::BTreeMap;
947 ///
948 /// let mut map = BTreeMap::new();
949 /// map.insert(1, "a");
950 /// map.insert(2, "b");
951 /// while let Some((key, _val)) = map.pop_last() {
952 /// assert!(map.iter().all(|(k, _v)| *k < key));
953 /// }
954 /// assert!(map.is_empty());
955 /// ```
956 #[stable(feature = "map_first_last", since = "1.66.0")]
957 pub fn pop_last(&mut self) -> Option<(K, V)>
958 where
959 K: Ord,
960 {
961 self.last_entry().map(|entry| entry.remove_entry())
962 }
963
964 /// Returns `true` if the map contains a value for the specified key.
965 ///
966 /// The key may be any borrowed form of the map's key type, but the ordering
967 /// on the borrowed form *must* match the ordering on the key type.
968 ///
969 /// # Examples
970 ///
971 /// ```
972 /// use std::collections::BTreeMap;
973 ///
974 /// let mut map = BTreeMap::new();
975 /// map.insert(1, "a");
976 /// assert_eq!(map.contains_key(&1), true);
977 /// assert_eq!(map.contains_key(&2), false);
978 /// ```
979 #[stable(feature = "rust1", since = "1.0.0")]
980 #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_contains_key")]
981 pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
982 where
983 K: Borrow<Q> + Ord,
984 Q: Ord,
985 {
986 self.get(key).is_some()
987 }
988
989 /// Returns a mutable reference to the value corresponding to the key.
990 ///
991 /// The key may be any borrowed form of the map's key type, but the ordering
992 /// on the borrowed form *must* match the ordering on the key type.
993 ///
994 /// # Examples
995 ///
996 /// ```
997 /// use std::collections::BTreeMap;
998 ///
999 /// let mut map = BTreeMap::new();
1000 /// map.insert(1, "a");
1001 /// if let Some(x) = map.get_mut(&1) {
1002 /// *x = "b";
1003 /// }
1004 /// assert_eq!(map[&1], "b");
1005 /// ```
1006 // See `get` for implementation notes, this is basically a copy-paste with mut's added
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
1009 where
1010 K: Borrow<Q> + Ord,
1011 Q: Ord,
1012 {
1013 let root_node = self.root.as_mut()?.borrow_mut();
1014 match root_node.search_tree(key) {
1015 Found(handle) => Some(handle.into_val_mut()),
1016 GoDown(_) => None,
1017 }
1018 }
1019
1020 /// Inserts a key-value pair into the map.
1021 ///
1022 /// If the map did not have this key present, `None` is returned.
1023 ///
1024 /// If the map did have this key present, the value is updated, and the old
1025 /// value is returned. The key is not updated, though; this matters for
1026 /// types that can be `==` without being identical. See the [module-level
1027 /// documentation] for more.
1028 ///
1029 /// [module-level documentation]: index.html#insert-and-complex-keys
1030 ///
1031 /// # Examples
1032 ///
1033 /// ```
1034 /// use std::collections::BTreeMap;
1035 ///
1036 /// let mut map = BTreeMap::new();
1037 /// assert_eq!(map.insert(37, "a"), None);
1038 /// assert_eq!(map.is_empty(), false);
1039 ///
1040 /// map.insert(37, "b");
1041 /// assert_eq!(map.insert(37, "c"), Some("b"));
1042 /// assert_eq!(map[&37], "c");
1043 /// ```
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 #[rustc_confusables("push", "put", "set")]
1046 #[cfg_attr(not(test), rustc_diagnostic_item = "btreemap_insert")]
1047 pub fn insert(&mut self, key: K, value: V) -> Option<V>
1048 where
1049 K: Ord,
1050 {
1051 match self.entry(key) {
1052 Occupied(mut entry) => Some(entry.insert(value)),
1053 Vacant(entry) => {
1054 entry.insert(value);
1055 None
1056 }
1057 }
1058 }
1059
1060 /// Tries to insert a key-value pair into the map, and returns
1061 /// a mutable reference to the value in the entry.
1062 ///
1063 /// If the map already had this key present, nothing is updated, and
1064 /// an error containing the occupied entry and the value is returned.
1065 ///
1066 /// # Examples
1067 ///
1068 /// ```
1069 /// #![feature(map_try_insert)]
1070 ///
1071 /// use std::collections::BTreeMap;
1072 ///
1073 /// let mut map = BTreeMap::new();
1074 /// assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
1075 ///
1076 /// let err = map.try_insert(37, "b").unwrap_err();
1077 /// assert_eq!(err.entry.key(), &37);
1078 /// assert_eq!(err.entry.get(), &"a");
1079 /// assert_eq!(err.value, "b");
1080 /// ```
1081 #[unstable(feature = "map_try_insert", issue = "82766")]
1082 pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, A>>
1083 where
1084 K: Ord,
1085 {
1086 match self.entry(key) {
1087 Occupied(entry) => Err(OccupiedError { entry, value }),
1088 Vacant(entry) => Ok(entry.insert(value)),
1089 }
1090 }
1091
1092 /// Removes a key from the map, returning the value at the key if the key
1093 /// was previously in the map.
1094 ///
1095 /// The key may be any borrowed form of the map's key type, but the ordering
1096 /// on the borrowed form *must* match the ordering on the key type.
1097 ///
1098 /// # Examples
1099 ///
1100 /// ```
1101 /// use std::collections::BTreeMap;
1102 ///
1103 /// let mut map = BTreeMap::new();
1104 /// map.insert(1, "a");
1105 /// assert_eq!(map.remove(&1), Some("a"));
1106 /// assert_eq!(map.remove(&1), None);
1107 /// ```
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 #[rustc_confusables("delete", "take")]
1110 pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
1111 where
1112 K: Borrow<Q> + Ord,
1113 Q: Ord,
1114 {
1115 self.remove_entry(key).map(|(_, v)| v)
1116 }
1117
1118 /// Removes a key from the map, returning the stored key and value if the key
1119 /// was previously in the map.
1120 ///
1121 /// The key may be any borrowed form of the map's key type, but the ordering
1122 /// on the borrowed form *must* match the ordering on the key type.
1123 ///
1124 /// # Examples
1125 ///
1126 /// ```
1127 /// use std::collections::BTreeMap;
1128 ///
1129 /// let mut map = BTreeMap::new();
1130 /// map.insert(1, "a");
1131 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
1132 /// assert_eq!(map.remove_entry(&1), None);
1133 /// ```
1134 #[stable(feature = "btreemap_remove_entry", since = "1.45.0")]
1135 pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
1136 where
1137 K: Borrow<Q> + Ord,
1138 Q: Ord,
1139 {
1140 let (map, dormant_map) = DormantMutRef::new(self);
1141 let root_node = map.root.as_mut()?.borrow_mut();
1142 match root_node.search_tree(key) {
1143 Found(handle) => Some(
1144 OccupiedEntry {
1145 handle,
1146 dormant_map,
1147 alloc: (*map.alloc).clone(),
1148 _marker: PhantomData,
1149 }
1150 .remove_entry(),
1151 ),
1152 GoDown(_) => None,
1153 }
1154 }
1155
1156 /// Retains only the elements specified by the predicate.
1157 ///
1158 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
1159 /// The elements are visited in ascending key order.
1160 ///
1161 /// # Examples
1162 ///
1163 /// ```
1164 /// use std::collections::BTreeMap;
1165 ///
1166 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();
1167 /// // Keep only the elements with even-numbered keys.
1168 /// map.retain(|&k, _| k % 2 == 0);
1169 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
1170 /// ```
1171 #[inline]
1172 #[stable(feature = "btree_retain", since = "1.53.0")]
1173 pub fn retain<F>(&mut self, mut f: F)
1174 where
1175 K: Ord,
1176 F: FnMut(&K, &mut V) -> bool,
1177 {
1178 self.extract_if(.., |k, v| !f(k, v)).for_each(drop);
1179 }
1180
1181 /// Moves all elements from `other` into `self`, leaving `other` empty.
1182 ///
1183 /// If a key from `other` is already present in `self`, the respective
1184 /// value from `self` will be overwritten with the respective value from `other`.
1185 /// Similar to [`insert`], though, the key is not overwritten,
1186 /// which matters for types that can be `==` without being identical.
1187 ///
1188 /// [`insert`]: BTreeMap::insert
1189 ///
1190 /// # Examples
1191 ///
1192 /// ```
1193 /// use std::collections::BTreeMap;
1194 ///
1195 /// let mut a = BTreeMap::new();
1196 /// a.insert(1, "a");
1197 /// a.insert(2, "b");
1198 /// a.insert(3, "c"); // Note: Key (3) also present in b.
1199 ///
1200 /// let mut b = BTreeMap::new();
1201 /// b.insert(3, "d"); // Note: Key (3) also present in a.
1202 /// b.insert(4, "e");
1203 /// b.insert(5, "f");
1204 ///
1205 /// a.append(&mut b);
1206 ///
1207 /// assert_eq!(a.len(), 5);
1208 /// assert_eq!(b.len(), 0);
1209 ///
1210 /// assert_eq!(a[&1], "a");
1211 /// assert_eq!(a[&2], "b");
1212 /// assert_eq!(a[&3], "d"); // Note: "c" has been overwritten.
1213 /// assert_eq!(a[&4], "e");
1214 /// assert_eq!(a[&5], "f");
1215 /// ```
1216 #[stable(feature = "btree_append", since = "1.11.0")]
1217 pub fn append(&mut self, other: &mut Self)
1218 where
1219 K: Ord,
1220 A: Clone,
1221 {
1222 let other = mem::replace(other, Self::new_in((*self.alloc).clone()));
1223 self.merge(other, |_key, _self_val, other_val| other_val);
1224 }
1225
1226 /// Moves all elements from `other` into `self`, leaving `other` empty.
1227 ///
1228 /// If a key from `other` is already present in `self`, then the `conflict`
1229 /// closure is used to return a value to `self`. The `conflict`
1230 /// closure takes in a borrow of `self`'s key, `self`'s value, and `other`'s value
1231 /// in that order.
1232 ///
1233 /// An example of why one might use this method over [`append`]
1234 /// is to combine `self`'s value with `other`'s value when their keys conflict.
1235 ///
1236 /// Similar to [`insert`], though, the key is not overwritten,
1237 /// which matters for types that can be `==` without being identical.
1238 ///
1239 /// [`insert`]: BTreeMap::insert
1240 /// [`append`]: BTreeMap::append
1241 ///
1242 /// # Examples
1243 ///
1244 /// ```
1245 /// #![feature(btree_merge)]
1246 /// use std::collections::BTreeMap;
1247 ///
1248 /// let mut a = BTreeMap::new();
1249 /// a.insert(1, String::from("a"));
1250 /// a.insert(2, String::from("b"));
1251 /// a.insert(3, String::from("c")); // Note: Key (3) also present in b.
1252 ///
1253 /// let mut b = BTreeMap::new();
1254 /// b.insert(3, String::from("d")); // Note: Key (3) also present in a.
1255 /// b.insert(4, String::from("e"));
1256 /// b.insert(5, String::from("f"));
1257 ///
1258 /// // concatenate a's value and b's value
1259 /// a.merge(b, |_, a_val, b_val| {
1260 /// format!("{a_val}{b_val}")
1261 /// });
1262 ///
1263 /// assert_eq!(a.len(), 5); // all of b's keys in a
1264 ///
1265 /// assert_eq!(a[&1], "a");
1266 /// assert_eq!(a[&2], "b");
1267 /// assert_eq!(a[&3], "cd"); // Note: "c" has been combined with "d".
1268 /// assert_eq!(a[&4], "e");
1269 /// assert_eq!(a[&5], "f");
1270 /// ```
1271 #[unstable(feature = "btree_merge", issue = "152152")]
1272 pub fn merge(&mut self, mut other: Self, mut conflict: impl FnMut(&K, V, V) -> V)
1273 where
1274 K: Ord,
1275 A: Clone,
1276 {
1277 // Do we have to append anything at all?
1278 if other.is_empty() {
1279 return;
1280 }
1281
1282 // We can just swap `self` and `other` if `self` is empty.
1283 if self.is_empty() {
1284 mem::swap(self, &mut other);
1285 return;
1286 }
1287
1288 let mut other_iter = other.into_iter();
1289 let (first_other_key, first_other_val) = other_iter.next().unwrap();
1290
1291 // find the first gap that has the smallest key greater than or equal to
1292 // the first key from other
1293 let mut self_cursor = self.lower_bound_mut(Bound::Included(&first_other_key));
1294
1295 if let Some((self_key, _)) = self_cursor.peek_next() {
1296 match K::cmp(self_key, &first_other_key) {
1297 Ordering::Equal => {
1298 // if `f` unwinds, the next entry is already removed leaving
1299 // the tree in valid state.
1300 // FIXME: Once `MaybeDangling` is implemented, we can optimize
1301 // this through using a drop handler and transmutating CursorMutKey<K, V>
1302 // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1303 if let Some((k, v)) = self_cursor.remove_next() {
1304 // SAFETY: we remove the K, V out of the next entry,
1305 // apply 'f' to get a new (K, V), and insert it back
1306 // into the next entry that the cursor is pointing at
1307 let v = conflict(&k, v, first_other_val);
1308 unsafe { self_cursor.insert_after_unchecked(k, v) };
1309 }
1310 }
1311 Ordering::Greater =>
1312 // SAFETY: we know our other_key's ordering is less than self_key,
1313 // so inserting before will guarantee sorted order
1314 unsafe {
1315 self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1316 },
1317 Ordering::Less => {
1318 unreachable!("Cursor's peek_next should return None.");
1319 }
1320 }
1321 } else {
1322 // SAFETY: reaching here means our cursor is at the end
1323 // self BTreeMap so we just insert other_key here
1324 unsafe {
1325 self_cursor.insert_before_unchecked(first_other_key, first_other_val);
1326 }
1327 }
1328
1329 for (other_key, other_val) in other_iter {
1330 loop {
1331 if let Some((self_key, _)) = self_cursor.peek_next() {
1332 match K::cmp(self_key, &other_key) {
1333 Ordering::Equal => {
1334 // if `f` unwinds, the next entry is already removed leaving
1335 // the tree in valid state.
1336 // FIXME: Once `MaybeDangling` is implemented, we can optimize
1337 // this through using a drop handler and transmutating CursorMutKey<K, V>
1338 // to CursorMutKey<ManuallyDrop<K>, ManuallyDrop<V>> (see PR #152418)
1339 if let Some((k, v)) = self_cursor.remove_next() {
1340 // SAFETY: we remove the K, V out of the next entry,
1341 // apply 'f' to get a new (K, V), and insert it back
1342 // into the next entry that the cursor is pointing at
1343 let v = conflict(&k, v, other_val);
1344 unsafe { self_cursor.insert_after_unchecked(k, v) };
1345 }
1346 break;
1347 }
1348 Ordering::Greater => {
1349 // SAFETY: we know our self_key's ordering is greater than other_key,
1350 // so inserting before will guarantee sorted order
1351 unsafe {
1352 self_cursor.insert_before_unchecked(other_key, other_val);
1353 }
1354 break;
1355 }
1356 Ordering::Less => {
1357 // FIXME: instead of doing a linear search here,
1358 // this can be optimized to search the tree by starting
1359 // from self_cursor and going towards the root and then
1360 // back down to the proper node -- that should probably
1361 // be a new method on Cursor*.
1362 self_cursor.next();
1363 }
1364 }
1365 } else {
1366 // FIXME: If we get here, that means all of other's keys are greater than
1367 // self's keys. For performance, this should really do a bulk insertion of items
1368 // from other_iter into the end of self `BTreeMap`. Maybe this should be
1369 // a method for Cursor*?
1370
1371 // SAFETY: reaching here means our cursor is at the end
1372 // self BTreeMap so we just insert other_key here
1373 unsafe {
1374 self_cursor.insert_before_unchecked(other_key, other_val);
1375 }
1376 break;
1377 }
1378 }
1379 }
1380 }
1381
1382 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1383 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1384 /// yield elements from min (inclusive) to max (exclusive).
1385 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1386 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1387 /// range from 4 to 10.
1388 ///
1389 /// # Panics
1390 ///
1391 /// Panics if range `start > end`.
1392 /// Panics if range `start == end` and both bounds are `Excluded`.
1393 ///
1394 /// # Examples
1395 ///
1396 /// ```
1397 /// use std::collections::BTreeMap;
1398 /// use std::ops::Bound::Included;
1399 ///
1400 /// let mut map = BTreeMap::new();
1401 /// map.insert(3, "a");
1402 /// map.insert(5, "b");
1403 /// map.insert(8, "c");
1404 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1405 /// println!("{key}: {value}");
1406 /// }
1407 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1408 /// ```
1409 #[stable(feature = "btree_range", since = "1.17.0")]
1410 pub fn range<T: ?Sized, R>(&self, range: R) -> Range<'_, K, V>
1411 where
1412 T: Ord,
1413 K: Borrow<T> + Ord,
1414 R: RangeBounds<T>,
1415 {
1416 if let Some(root) = &self.root {
1417 Range { inner: root.reborrow().range_search(range) }
1418 } else {
1419 Range { inner: LeafRange::none() }
1420 }
1421 }
1422
1423 /// Constructs a mutable double-ended iterator over a sub-range of elements in the map.
1424 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1425 /// yield elements from min (inclusive) to max (exclusive).
1426 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1427 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1428 /// range from 4 to 10.
1429 ///
1430 /// # Panics
1431 ///
1432 /// Panics if range `start > end`.
1433 /// Panics if range `start == end` and both bounds are `Excluded`.
1434 ///
1435 /// # Examples
1436 ///
1437 /// ```
1438 /// use std::collections::BTreeMap;
1439 ///
1440 /// let mut map: BTreeMap<&str, i32> =
1441 /// [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into();
1442 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1443 /// *balance += 100;
1444 /// }
1445 /// for (name, balance) in &map {
1446 /// println!("{name} => {balance}");
1447 /// }
1448 /// ```
1449 #[stable(feature = "btree_range", since = "1.17.0")]
1450 pub fn range_mut<T: ?Sized, R>(&mut self, range: R) -> RangeMut<'_, K, V>
1451 where
1452 T: Ord,
1453 K: Borrow<T> + Ord,
1454 R: RangeBounds<T>,
1455 {
1456 if let Some(root) = &mut self.root {
1457 RangeMut { inner: root.borrow_valmut().range_search(range), _marker: PhantomData }
1458 } else {
1459 RangeMut { inner: LeafRange::none(), _marker: PhantomData }
1460 }
1461 }
1462
1463 /// Gets the given key's corresponding entry in the map for in-place manipulation.
1464 ///
1465 /// # Examples
1466 ///
1467 /// ```
1468 /// use std::collections::BTreeMap;
1469 ///
1470 /// let mut count: BTreeMap<&str, usize> = BTreeMap::new();
1471 ///
1472 /// // count the number of occurrences of letters in the vec
1473 /// for x in ["a", "b", "a", "c", "a", "b"] {
1474 /// count.entry(x).and_modify(|curr| *curr += 1).or_insert(1);
1475 /// }
1476 ///
1477 /// assert_eq!(count["a"], 3);
1478 /// assert_eq!(count["b"], 2);
1479 /// assert_eq!(count["c"], 1);
1480 /// ```
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A>
1483 where
1484 K: Ord,
1485 {
1486 let (map, dormant_map) = DormantMutRef::new(self);
1487 match map.root {
1488 None => Vacant(VacantEntry {
1489 key,
1490 handle: None,
1491 dormant_map,
1492 alloc: (*map.alloc).clone(),
1493 _marker: PhantomData,
1494 }),
1495 Some(ref mut root) => match root.borrow_mut().search_tree(&key) {
1496 Found(handle) => Occupied(OccupiedEntry {
1497 handle,
1498 dormant_map,
1499 alloc: (*map.alloc).clone(),
1500 _marker: PhantomData,
1501 }),
1502 GoDown(handle) => Vacant(VacantEntry {
1503 key,
1504 handle: Some(handle),
1505 dormant_map,
1506 alloc: (*map.alloc).clone(),
1507 _marker: PhantomData,
1508 }),
1509 },
1510 }
1511 }
1512
1513 /// Splits the collection into two at the given key. Returns everything after the given key,
1514 /// including the key. If the key is not present, the split will occur at the nearest
1515 /// greater key, or return an empty map if no such key exists.
1516 ///
1517 /// # Examples
1518 ///
1519 /// ```
1520 /// use std::collections::BTreeMap;
1521 ///
1522 /// let mut a = BTreeMap::new();
1523 /// a.insert(1, "a");
1524 /// a.insert(2, "b");
1525 /// a.insert(3, "c");
1526 /// a.insert(17, "d");
1527 /// a.insert(41, "e");
1528 ///
1529 /// let b = a.split_off(&3);
1530 ///
1531 /// assert_eq!(a.len(), 2);
1532 /// assert_eq!(b.len(), 3);
1533 ///
1534 /// assert_eq!(a[&1], "a");
1535 /// assert_eq!(a[&2], "b");
1536 ///
1537 /// assert_eq!(b[&3], "c");
1538 /// assert_eq!(b[&17], "d");
1539 /// assert_eq!(b[&41], "e");
1540 /// ```
1541 #[stable(feature = "btree_split_off", since = "1.11.0")]
1542 pub fn split_off<Q: ?Sized + Ord>(&mut self, key: &Q) -> Self
1543 where
1544 K: Borrow<Q> + Ord,
1545 A: Clone,
1546 {
1547 if self.is_empty() {
1548 return Self::new_in((*self.alloc).clone());
1549 }
1550
1551 let total_num = self.len();
1552 let left_root = self.root.as_mut().unwrap(); // unwrap succeeds because not empty
1553
1554 let right_root = left_root.split_off(key, (*self.alloc).clone());
1555
1556 let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
1557 self.length = new_left_len;
1558
1559 BTreeMap {
1560 root: Some(right_root),
1561 length: right_len,
1562 alloc: self.alloc.clone(),
1563 _marker: PhantomData,
1564 }
1565 }
1566
1567 /// Creates an iterator that visits elements (key-value pairs) in the specified range in
1568 /// ascending key order and uses a closure to determine if an element
1569 /// should be removed.
1570 ///
1571 /// If the closure returns `true`, the element is removed from the map and
1572 /// yielded. If the closure returns `false`, or panics, the element remains
1573 /// in the map and will not be yielded.
1574 ///
1575 /// The iterator also lets you mutate the value of each element in the
1576 /// closure, regardless of whether you choose to keep or remove it.
1577 ///
1578 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
1579 /// or the iteration short-circuits, then the remaining elements will be retained.
1580 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
1581 /// or [`retain`] with a negated predicate if you also do not need to restrict the range.
1582 ///
1583 /// [`retain`]: BTreeMap::retain
1584 ///
1585 /// # Examples
1586 ///
1587 /// ```
1588 /// use std::collections::BTreeMap;
1589 ///
1590 /// // Splitting a map into even and odd keys, reusing the original map:
1591 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1592 /// let evens: BTreeMap<_, _> = map.extract_if(.., |k, _v| k % 2 == 0).collect();
1593 /// let odds = map;
1594 /// assert_eq!(evens.keys().copied().collect::<Vec<_>>(), [0, 2, 4, 6]);
1595 /// assert_eq!(odds.keys().copied().collect::<Vec<_>>(), [1, 3, 5, 7]);
1596 ///
1597 /// // Splitting a map into low and high halves, reusing the original map:
1598 /// let mut map: BTreeMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
1599 /// let low: BTreeMap<_, _> = map.extract_if(0..4, |_k, _v| true).collect();
1600 /// let high = map;
1601 /// assert_eq!(low.keys().copied().collect::<Vec<_>>(), [0, 1, 2, 3]);
1602 /// assert_eq!(high.keys().copied().collect::<Vec<_>>(), [4, 5, 6, 7]);
1603 /// ```
1604 #[stable(feature = "btree_extract_if", since = "1.91.0")]
1605 pub fn extract_if<F, R>(&mut self, range: R, pred: F) -> ExtractIf<'_, K, V, R, F, A>
1606 where
1607 K: Ord,
1608 R: RangeBounds<K>,
1609 F: FnMut(&K, &mut V) -> bool,
1610 {
1611 let (inner, alloc) = self.extract_if_inner(range);
1612 ExtractIf { pred, inner, alloc }
1613 }
1614
1615 pub(super) fn extract_if_inner<R>(&mut self, range: R) -> (ExtractIfInner<'_, K, V, R>, A)
1616 where
1617 K: Ord,
1618 R: RangeBounds<K>,
1619 {
1620 if let Some(root) = self.root.as_mut() {
1621 let (root, dormant_root) = DormantMutRef::new(root);
1622 let first = root.borrow_mut().lower_bound(SearchBound::from_range(range.start_bound()));
1623 (
1624 ExtractIfInner {
1625 length: &mut self.length,
1626 dormant_root: Some(dormant_root),
1627 cur_leaf_edge: Some(first),
1628 range,
1629 },
1630 (*self.alloc).clone(),
1631 )
1632 } else {
1633 (
1634 ExtractIfInner {
1635 length: &mut self.length,
1636 dormant_root: None,
1637 cur_leaf_edge: None,
1638 range,
1639 },
1640 (*self.alloc).clone(),
1641 )
1642 }
1643 }
1644
1645 /// Creates a consuming iterator visiting all the keys, in sorted order.
1646 /// The map cannot be used after calling this.
1647 /// The iterator element type is `K`.
1648 ///
1649 /// # Examples
1650 ///
1651 /// ```
1652 /// use std::collections::BTreeMap;
1653 ///
1654 /// let mut a = BTreeMap::new();
1655 /// a.insert(2, "b");
1656 /// a.insert(1, "a");
1657 ///
1658 /// let keys: Vec<i32> = a.into_keys().collect();
1659 /// assert_eq!(keys, [1, 2]);
1660 /// ```
1661 #[inline]
1662 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1663 pub fn into_keys(self) -> IntoKeys<K, V, A> {
1664 IntoKeys { inner: self.into_iter() }
1665 }
1666
1667 /// Creates a consuming iterator visiting all the values, in order by key.
1668 /// The map cannot be used after calling this.
1669 /// The iterator element type is `V`.
1670 ///
1671 /// # Examples
1672 ///
1673 /// ```
1674 /// use std::collections::BTreeMap;
1675 ///
1676 /// let mut a = BTreeMap::new();
1677 /// a.insert(1, "hello");
1678 /// a.insert(2, "goodbye");
1679 ///
1680 /// let values: Vec<&str> = a.into_values().collect();
1681 /// assert_eq!(values, ["hello", "goodbye"]);
1682 /// ```
1683 #[inline]
1684 #[stable(feature = "map_into_keys_values", since = "1.54.0")]
1685 pub fn into_values(self) -> IntoValues<K, V, A> {
1686 IntoValues { inner: self.into_iter() }
1687 }
1688
1689 /// Makes a `BTreeMap` from a sorted iterator.
1690 pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I, alloc: A) -> Self
1691 where
1692 K: Ord,
1693 I: IntoIterator<Item = (K, V)>,
1694 {
1695 let mut root = Root::new(alloc.clone());
1696 let mut length = 0;
1697 root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length, alloc.clone());
1698 BTreeMap { root: Some(root), length, alloc: ManuallyDrop::new(alloc), _marker: PhantomData }
1699 }
1700}
1701
1702#[stable(feature = "rust1", since = "1.0.0")]
1703impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a BTreeMap<K, V, A> {
1704 type Item = (&'a K, &'a V);
1705 type IntoIter = Iter<'a, K, V>;
1706
1707 fn into_iter(self) -> Iter<'a, K, V> {
1708 self.iter()
1709 }
1710}
1711
1712#[stable(feature = "rust1", since = "1.0.0")]
1713impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> {
1714 type Item = (&'a K, &'a V);
1715
1716 fn next(&mut self) -> Option<(&'a K, &'a V)> {
1717 if self.length == 0 {
1718 None
1719 } else {
1720 self.length -= 1;
1721 Some(unsafe { self.range.next_unchecked() })
1722 }
1723 }
1724
1725 fn size_hint(&self) -> (usize, Option<usize>) {
1726 (self.length, Some(self.length))
1727 }
1728
1729 fn last(mut self) -> Option<(&'a K, &'a V)> {
1730 self.next_back()
1731 }
1732
1733 fn min(mut self) -> Option<(&'a K, &'a V)>
1734 where
1735 (&'a K, &'a V): Ord,
1736 {
1737 self.next()
1738 }
1739
1740 fn max(mut self) -> Option<(&'a K, &'a V)>
1741 where
1742 (&'a K, &'a V): Ord,
1743 {
1744 self.next_back()
1745 }
1746}
1747
1748#[stable(feature = "fused", since = "1.26.0")]
1749impl<K, V> FusedIterator for Iter<'_, K, V> {}
1750
1751#[stable(feature = "rust1", since = "1.0.0")]
1752impl<'a, K: 'a, V: 'a> DoubleEndedIterator for Iter<'a, K, V> {
1753 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1754 if self.length == 0 {
1755 None
1756 } else {
1757 self.length -= 1;
1758 Some(unsafe { self.range.next_back_unchecked() })
1759 }
1760 }
1761}
1762
1763#[stable(feature = "rust1", since = "1.0.0")]
1764impl<K, V> ExactSizeIterator for Iter<'_, K, V> {
1765 fn len(&self) -> usize {
1766 self.length
1767 }
1768}
1769
1770#[unstable(feature = "trusted_len", issue = "37572")]
1771unsafe impl<K, V> TrustedLen for Iter<'_, K, V> {}
1772
1773#[stable(feature = "rust1", since = "1.0.0")]
1774impl<K, V> Clone for Iter<'_, K, V> {
1775 fn clone(&self) -> Self {
1776 Iter { range: self.range.clone(), length: self.length }
1777 }
1778}
1779
1780#[stable(feature = "rust1", since = "1.0.0")]
1781impl<'a, K, V, A: Allocator + Clone> IntoIterator for &'a mut BTreeMap<K, V, A> {
1782 type Item = (&'a K, &'a mut V);
1783 type IntoIter = IterMut<'a, K, V>;
1784
1785 fn into_iter(self) -> IterMut<'a, K, V> {
1786 self.iter_mut()
1787 }
1788}
1789
1790#[stable(feature = "rust1", since = "1.0.0")]
1791impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1792 type Item = (&'a K, &'a mut V);
1793
1794 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1795 if self.length == 0 {
1796 None
1797 } else {
1798 self.length -= 1;
1799 Some(unsafe { self.range.next_unchecked() })
1800 }
1801 }
1802
1803 fn size_hint(&self) -> (usize, Option<usize>) {
1804 (self.length, Some(self.length))
1805 }
1806
1807 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
1808 self.next_back()
1809 }
1810
1811 fn min(mut self) -> Option<(&'a K, &'a mut V)>
1812 where
1813 (&'a K, &'a mut V): Ord,
1814 {
1815 self.next()
1816 }
1817
1818 fn max(mut self) -> Option<(&'a K, &'a mut V)>
1819 where
1820 (&'a K, &'a mut V): Ord,
1821 {
1822 self.next_back()
1823 }
1824}
1825
1826#[stable(feature = "rust1", since = "1.0.0")]
1827impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1828 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1829 if self.length == 0 {
1830 None
1831 } else {
1832 self.length -= 1;
1833 Some(unsafe { self.range.next_back_unchecked() })
1834 }
1835 }
1836}
1837
1838#[stable(feature = "rust1", since = "1.0.0")]
1839impl<K, V> ExactSizeIterator for IterMut<'_, K, V> {
1840 fn len(&self) -> usize {
1841 self.length
1842 }
1843}
1844
1845#[unstable(feature = "trusted_len", issue = "37572")]
1846unsafe impl<K, V> TrustedLen for IterMut<'_, K, V> {}
1847
1848#[stable(feature = "fused", since = "1.26.0")]
1849impl<K, V> FusedIterator for IterMut<'_, K, V> {}
1850
1851impl<'a, K, V> IterMut<'a, K, V> {
1852 /// Returns an iterator of references over the remaining items.
1853 #[inline]
1854 pub(super) fn iter(&self) -> Iter<'_, K, V> {
1855 Iter { range: self.range.reborrow(), length: self.length }
1856 }
1857}
1858
1859#[stable(feature = "rust1", since = "1.0.0")]
1860impl<K, V, A: Allocator + Clone> IntoIterator for BTreeMap<K, V, A> {
1861 type Item = (K, V);
1862 type IntoIter = IntoIter<K, V, A>;
1863
1864 /// Gets an owning iterator over the entries of the map, sorted by key.
1865 fn into_iter(self) -> IntoIter<K, V, A> {
1866 let mut me = ManuallyDrop::new(self);
1867 if let Some(root) = me.root.take() {
1868 let full_range = root.into_dying().full_range();
1869
1870 IntoIter {
1871 range: full_range,
1872 length: me.length,
1873 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1874 }
1875 } else {
1876 IntoIter {
1877 range: LazyLeafRange::none(),
1878 length: 0,
1879 alloc: unsafe { ManuallyDrop::take(&mut me.alloc) },
1880 }
1881 }
1882 }
1883}
1884
1885#[stable(feature = "btree_drop", since = "1.7.0")]
1886impl<K, V, A: Allocator + Clone> Drop for IntoIter<K, V, A> {
1887 fn drop(&mut self) {
1888 struct DropGuard<'a, K, V, A: Allocator + Clone>(&'a mut IntoIter<K, V, A>);
1889
1890 impl<'a, K, V, A: Allocator + Clone> Drop for DropGuard<'a, K, V, A> {
1891 fn drop(&mut self) {
1892 // Continue the same loop we perform below. This only runs when unwinding, so we
1893 // don't have to care about panics this time (they'll abort).
1894 while let Some(kv) = self.0.dying_next() {
1895 // SAFETY: we consume the dying handle immediately.
1896 unsafe { kv.drop_key_val() };
1897 }
1898 }
1899 }
1900
1901 while let Some(kv) = self.dying_next() {
1902 let guard = DropGuard(self);
1903 // SAFETY: we don't touch the tree before consuming the dying handle.
1904 unsafe { kv.drop_key_val() };
1905 mem::forget(guard);
1906 }
1907 }
1908}
1909
1910impl<K, V, A: Allocator + Clone> IntoIter<K, V, A> {
1911 /// Core of a `next` method returning a dying KV handle,
1912 /// invalidated by further calls to this function and some others.
1913 fn dying_next(
1914 &mut self,
1915 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1916 if self.length == 0 {
1917 self.range.deallocating_end(self.alloc.clone());
1918 None
1919 } else {
1920 self.length -= 1;
1921 Some(unsafe { self.range.deallocating_next_unchecked(self.alloc.clone()) })
1922 }
1923 }
1924
1925 /// Core of a `next_back` method returning a dying KV handle,
1926 /// invalidated by further calls to this function and some others.
1927 fn dying_next_back(
1928 &mut self,
1929 ) -> Option<Handle<NodeRef<marker::Dying, K, V, marker::LeafOrInternal>, marker::KV>> {
1930 if self.length == 0 {
1931 self.range.deallocating_end(self.alloc.clone());
1932 None
1933 } else {
1934 self.length -= 1;
1935 Some(unsafe { self.range.deallocating_next_back_unchecked(self.alloc.clone()) })
1936 }
1937 }
1938}
1939
1940#[stable(feature = "rust1", since = "1.0.0")]
1941impl<K, V, A: Allocator + Clone> Iterator for IntoIter<K, V, A> {
1942 type Item = (K, V);
1943
1944 fn next(&mut self) -> Option<(K, V)> {
1945 // SAFETY: we consume the dying handle immediately.
1946 self.dying_next().map(unsafe { |kv| kv.into_key_val() })
1947 }
1948
1949 fn size_hint(&self) -> (usize, Option<usize>) {
1950 (self.length, Some(self.length))
1951 }
1952}
1953
1954#[stable(feature = "rust1", since = "1.0.0")]
1955impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoIter<K, V, A> {
1956 fn next_back(&mut self) -> Option<(K, V)> {
1957 // SAFETY: we consume the dying handle immediately.
1958 self.dying_next_back().map(unsafe { |kv| kv.into_key_val() })
1959 }
1960}
1961
1962#[stable(feature = "rust1", since = "1.0.0")]
1963impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoIter<K, V, A> {
1964 fn len(&self) -> usize {
1965 self.length
1966 }
1967}
1968
1969#[unstable(feature = "trusted_len", issue = "37572")]
1970unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoIter<K, V, A> {}
1971
1972#[stable(feature = "fused", since = "1.26.0")]
1973impl<K, V, A: Allocator + Clone> FusedIterator for IntoIter<K, V, A> {}
1974
1975#[stable(feature = "rust1", since = "1.0.0")]
1976impl<'a, K, V> Iterator for Keys<'a, K, V> {
1977 type Item = &'a K;
1978
1979 fn next(&mut self) -> Option<&'a K> {
1980 self.inner.next().map(|(k, _)| k)
1981 }
1982
1983 fn size_hint(&self) -> (usize, Option<usize>) {
1984 self.inner.size_hint()
1985 }
1986
1987 fn last(mut self) -> Option<&'a K> {
1988 self.next_back()
1989 }
1990
1991 fn min(mut self) -> Option<&'a K>
1992 where
1993 &'a K: Ord,
1994 {
1995 self.next()
1996 }
1997
1998 fn max(mut self) -> Option<&'a K>
1999 where
2000 &'a K: Ord,
2001 {
2002 self.next_back()
2003 }
2004}
2005
2006#[stable(feature = "rust1", since = "1.0.0")]
2007impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
2008 fn next_back(&mut self) -> Option<&'a K> {
2009 self.inner.next_back().map(|(k, _)| k)
2010 }
2011}
2012
2013#[stable(feature = "rust1", since = "1.0.0")]
2014impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
2015 fn len(&self) -> usize {
2016 self.inner.len()
2017 }
2018}
2019
2020#[unstable(feature = "trusted_len", issue = "37572")]
2021unsafe impl<K, V> TrustedLen for Keys<'_, K, V> {}
2022
2023#[stable(feature = "fused", since = "1.26.0")]
2024impl<K, V> FusedIterator for Keys<'_, K, V> {}
2025
2026#[stable(feature = "rust1", since = "1.0.0")]
2027impl<K, V> Clone for Keys<'_, K, V> {
2028 fn clone(&self) -> Self {
2029 Keys { inner: self.inner.clone() }
2030 }
2031}
2032
2033#[stable(feature = "default_iters", since = "1.70.0")]
2034impl<K, V> Default for Keys<'_, K, V> {
2035 /// Creates an empty `btree_map::Keys`.
2036 ///
2037 /// ```
2038 /// # use std::collections::btree_map;
2039 /// let iter: btree_map::Keys<'_, u8, u8> = Default::default();
2040 /// assert_eq!(iter.len(), 0);
2041 /// ```
2042 fn default() -> Self {
2043 Keys { inner: Default::default() }
2044 }
2045}
2046
2047#[stable(feature = "rust1", since = "1.0.0")]
2048impl<'a, K, V> Iterator for Values<'a, K, V> {
2049 type Item = &'a V;
2050
2051 fn next(&mut self) -> Option<&'a V> {
2052 self.inner.next().map(|(_, v)| v)
2053 }
2054
2055 fn size_hint(&self) -> (usize, Option<usize>) {
2056 self.inner.size_hint()
2057 }
2058
2059 fn last(mut self) -> Option<&'a V> {
2060 self.next_back()
2061 }
2062}
2063
2064#[stable(feature = "rust1", since = "1.0.0")]
2065impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
2066 fn next_back(&mut self) -> Option<&'a V> {
2067 self.inner.next_back().map(|(_, v)| v)
2068 }
2069}
2070
2071#[stable(feature = "rust1", since = "1.0.0")]
2072impl<K, V> ExactSizeIterator for Values<'_, K, V> {
2073 fn len(&self) -> usize {
2074 self.inner.len()
2075 }
2076}
2077
2078#[unstable(feature = "trusted_len", issue = "37572")]
2079unsafe impl<K, V> TrustedLen for Values<'_, K, V> {}
2080
2081#[stable(feature = "fused", since = "1.26.0")]
2082impl<K, V> FusedIterator for Values<'_, K, V> {}
2083
2084#[stable(feature = "rust1", since = "1.0.0")]
2085impl<K, V> Clone for Values<'_, K, V> {
2086 fn clone(&self) -> Self {
2087 Values { inner: self.inner.clone() }
2088 }
2089}
2090
2091#[stable(feature = "default_iters", since = "1.70.0")]
2092impl<K, V> Default for Values<'_, K, V> {
2093 /// Creates an empty `btree_map::Values`.
2094 ///
2095 /// ```
2096 /// # use std::collections::btree_map;
2097 /// let iter: btree_map::Values<'_, u8, u8> = Default::default();
2098 /// assert_eq!(iter.len(), 0);
2099 /// ```
2100 fn default() -> Self {
2101 Values { inner: Default::default() }
2102 }
2103}
2104
2105/// An iterator produced by calling `extract_if` on BTreeMap.
2106#[stable(feature = "btree_extract_if", since = "1.91.0")]
2107#[must_use = "iterators are lazy and do nothing unless consumed; \
2108 use `retain` or `extract_if().for_each(drop)` to remove and discard elements"]
2109pub struct ExtractIf<
2110 'a,
2111 K,
2112 V,
2113 R,
2114 F,
2115 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
2116> {
2117 pred: F,
2118 inner: ExtractIfInner<'a, K, V, R>,
2119 /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
2120 alloc: A,
2121}
2122
2123/// Most of the implementation of ExtractIf are generic over the type
2124/// of the predicate, thus also serving for BTreeSet::ExtractIf.
2125pub(super) struct ExtractIfInner<'a, K, V, R> {
2126 /// Reference to the length field in the borrowed map, updated live.
2127 length: &'a mut usize,
2128 /// Buried reference to the root field in the borrowed map.
2129 /// Wrapped in `Option` to allow drop handler to `take` it.
2130 dormant_root: Option<DormantMutRef<'a, Root<K, V>>>,
2131 /// Contains a leaf edge preceding the next element to be returned, or the last leaf edge.
2132 /// Empty if the map has no root, if iteration went beyond the last leaf edge,
2133 /// or if a panic occurred in the predicate.
2134 cur_leaf_edge: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
2135 /// Range over which iteration was requested. We don't need the left side, but we
2136 /// can't extract the right side without requiring K: Clone.
2137 range: R,
2138}
2139
2140#[stable(feature = "btree_extract_if", since = "1.91.0")]
2141impl<K, V, R, F, A> fmt::Debug for ExtractIf<'_, K, V, R, F, A>
2142where
2143 K: fmt::Debug,
2144 V: fmt::Debug,
2145 A: Allocator + Clone,
2146{
2147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2148 f.debug_struct("ExtractIf").field("peek", &self.inner.peek()).finish_non_exhaustive()
2149 }
2150}
2151
2152#[stable(feature = "btree_extract_if", since = "1.91.0")]
2153impl<K, V, R, F, A: Allocator + Clone> Iterator for ExtractIf<'_, K, V, R, F, A>
2154where
2155 K: PartialOrd,
2156 R: RangeBounds<K>,
2157 F: FnMut(&K, &mut V) -> bool,
2158{
2159 type Item = (K, V);
2160
2161 fn next(&mut self) -> Option<(K, V)> {
2162 self.inner.next(&mut self.pred, self.alloc.clone())
2163 }
2164
2165 fn size_hint(&self) -> (usize, Option<usize>) {
2166 self.inner.size_hint()
2167 }
2168}
2169
2170impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
2171 /// Allow Debug implementations to predict the next element.
2172 pub(super) fn peek(&self) -> Option<(&K, &V)> {
2173 let edge = self.cur_leaf_edge.as_ref()?;
2174 edge.reborrow().next_kv().ok().map(Handle::into_kv)
2175 }
2176
2177 /// Implementation of a typical `ExtractIf::next` method, given the predicate.
2178 pub(super) fn next<F, A: Allocator + Clone>(&mut self, pred: &mut F, alloc: A) -> Option<(K, V)>
2179 where
2180 K: PartialOrd,
2181 R: RangeBounds<K>,
2182 F: FnMut(&K, &mut V) -> bool,
2183 {
2184 while let Ok(mut kv) = self.cur_leaf_edge.take()?.next_kv() {
2185 let (k, v) = kv.kv_mut();
2186
2187 // On creation, we navigated directly to the left bound, so we need only check the
2188 // right bound here to decide whether to stop.
2189 match self.range.end_bound() {
2190 Bound::Included(ref end) if (*k).le(end) => (),
2191 Bound::Excluded(ref end) if (*k).lt(end) => (),
2192 Bound::Unbounded => (),
2193 _ => return None,
2194 }
2195
2196 if pred(k, v) {
2197 *self.length -= 1;
2198 let (kv, pos) = kv.remove_kv_tracking(
2199 || {
2200 // SAFETY: we will touch the root in a way that will not
2201 // invalidate the position returned.
2202 let root = unsafe { self.dormant_root.take().unwrap().awaken() };
2203 root.pop_internal_level(alloc.clone());
2204 self.dormant_root = Some(DormantMutRef::new(root).1);
2205 },
2206 alloc.clone(),
2207 );
2208 self.cur_leaf_edge = Some(pos);
2209 return Some(kv);
2210 }
2211 self.cur_leaf_edge = Some(kv.next_leaf_edge());
2212 }
2213 None
2214 }
2215
2216 /// Implementation of a typical `ExtractIf::size_hint` method.
2217 pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
2218 // In most of the btree iterators, `self.length` is the number of elements
2219 // yet to be visited. Here, it includes elements that were visited and that
2220 // the predicate decided not to drain. Making this upper bound more tight
2221 // during iteration would require an extra field.
2222 (0, Some(*self.length))
2223 }
2224}
2225
2226#[stable(feature = "btree_extract_if", since = "1.91.0")]
2227impl<K, V, R, F> FusedIterator for ExtractIf<'_, K, V, R, F>
2228where
2229 K: PartialOrd,
2230 R: RangeBounds<K>,
2231 F: FnMut(&K, &mut V) -> bool,
2232{
2233}
2234
2235#[stable(feature = "btree_range", since = "1.17.0")]
2236impl<'a, K, V> Iterator for Range<'a, K, V> {
2237 type Item = (&'a K, &'a V);
2238
2239 fn next(&mut self) -> Option<(&'a K, &'a V)> {
2240 self.inner.next_checked()
2241 }
2242
2243 fn last(mut self) -> Option<(&'a K, &'a V)> {
2244 self.next_back()
2245 }
2246
2247 fn min(mut self) -> Option<(&'a K, &'a V)>
2248 where
2249 (&'a K, &'a V): Ord,
2250 {
2251 self.next()
2252 }
2253
2254 fn max(mut self) -> Option<(&'a K, &'a V)>
2255 where
2256 (&'a K, &'a V): Ord,
2257 {
2258 self.next_back()
2259 }
2260}
2261
2262#[stable(feature = "default_iters", since = "1.70.0")]
2263impl<K, V> Default for Range<'_, K, V> {
2264 /// Creates an empty `btree_map::Range`.
2265 ///
2266 /// ```
2267 /// # use std::collections::btree_map;
2268 /// let iter: btree_map::Range<'_, u8, u8> = Default::default();
2269 /// assert_eq!(iter.count(), 0);
2270 /// ```
2271 fn default() -> Self {
2272 Range { inner: Default::default() }
2273 }
2274}
2275
2276#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2277impl<K, V> Default for RangeMut<'_, K, V> {
2278 /// Creates an empty `btree_map::RangeMut`.
2279 ///
2280 /// ```
2281 /// # use std::collections::btree_map;
2282 /// let iter: btree_map::RangeMut<'_, u8, u8> = Default::default();
2283 /// assert_eq!(iter.count(), 0);
2284 /// ```
2285 fn default() -> Self {
2286 RangeMut { inner: Default::default(), _marker: PhantomData }
2287 }
2288}
2289
2290#[stable(feature = "map_values_mut", since = "1.10.0")]
2291impl<'a, K, V> Iterator for ValuesMut<'a, K, V> {
2292 type Item = &'a mut V;
2293
2294 fn next(&mut self) -> Option<&'a mut V> {
2295 self.inner.next().map(|(_, v)| v)
2296 }
2297
2298 fn size_hint(&self) -> (usize, Option<usize>) {
2299 self.inner.size_hint()
2300 }
2301
2302 fn last(mut self) -> Option<&'a mut V> {
2303 self.next_back()
2304 }
2305}
2306
2307#[stable(feature = "map_values_mut", since = "1.10.0")]
2308impl<'a, K, V> DoubleEndedIterator for ValuesMut<'a, K, V> {
2309 fn next_back(&mut self) -> Option<&'a mut V> {
2310 self.inner.next_back().map(|(_, v)| v)
2311 }
2312}
2313
2314#[stable(feature = "map_values_mut", since = "1.10.0")]
2315impl<K, V> ExactSizeIterator for ValuesMut<'_, K, V> {
2316 fn len(&self) -> usize {
2317 self.inner.len()
2318 }
2319}
2320
2321#[unstable(feature = "trusted_len", issue = "37572")]
2322unsafe impl<K, V> TrustedLen for ValuesMut<'_, K, V> {}
2323
2324#[stable(feature = "fused", since = "1.26.0")]
2325impl<K, V> FusedIterator for ValuesMut<'_, K, V> {}
2326
2327#[stable(feature = "default_iters_sequel", since = "1.82.0")]
2328impl<K, V> Default for ValuesMut<'_, K, V> {
2329 /// Creates an empty `btree_map::ValuesMut`.
2330 ///
2331 /// ```
2332 /// # use std::collections::btree_map;
2333 /// let iter: btree_map::ValuesMut<'_, u8, u8> = Default::default();
2334 /// assert_eq!(iter.count(), 0);
2335 /// ```
2336 fn default() -> Self {
2337 ValuesMut { inner: Default::default() }
2338 }
2339}
2340
2341#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2342impl<K, V, A: Allocator + Clone> Iterator for IntoKeys<K, V, A> {
2343 type Item = K;
2344
2345 fn next(&mut self) -> Option<K> {
2346 self.inner.next().map(|(k, _)| k)
2347 }
2348
2349 fn size_hint(&self) -> (usize, Option<usize>) {
2350 self.inner.size_hint()
2351 }
2352
2353 fn last(mut self) -> Option<K> {
2354 self.next_back()
2355 }
2356
2357 fn min(mut self) -> Option<K>
2358 where
2359 K: Ord,
2360 {
2361 self.next()
2362 }
2363
2364 fn max(mut self) -> Option<K>
2365 where
2366 K: Ord,
2367 {
2368 self.next_back()
2369 }
2370}
2371
2372#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2373impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoKeys<K, V, A> {
2374 fn next_back(&mut self) -> Option<K> {
2375 self.inner.next_back().map(|(k, _)| k)
2376 }
2377}
2378
2379#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2380impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoKeys<K, V, A> {
2381 fn len(&self) -> usize {
2382 self.inner.len()
2383 }
2384}
2385
2386#[unstable(feature = "trusted_len", issue = "37572")]
2387unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoKeys<K, V, A> {}
2388
2389#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2390impl<K, V, A: Allocator + Clone> FusedIterator for IntoKeys<K, V, A> {}
2391
2392#[stable(feature = "default_iters", since = "1.70.0")]
2393impl<K, V, A> Default for IntoKeys<K, V, A>
2394where
2395 A: Allocator + Default + Clone,
2396{
2397 /// Creates an empty `btree_map::IntoKeys`.
2398 ///
2399 /// ```
2400 /// # use std::collections::btree_map;
2401 /// let iter: btree_map::IntoKeys<u8, u8> = Default::default();
2402 /// assert_eq!(iter.len(), 0);
2403 /// ```
2404 fn default() -> Self {
2405 IntoKeys { inner: Default::default() }
2406 }
2407}
2408
2409#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2410impl<K, V, A: Allocator + Clone> Iterator for IntoValues<K, V, A> {
2411 type Item = V;
2412
2413 fn next(&mut self) -> Option<V> {
2414 self.inner.next().map(|(_, v)| v)
2415 }
2416
2417 fn size_hint(&self) -> (usize, Option<usize>) {
2418 self.inner.size_hint()
2419 }
2420
2421 fn last(mut self) -> Option<V> {
2422 self.next_back()
2423 }
2424}
2425
2426#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2427impl<K, V, A: Allocator + Clone> DoubleEndedIterator for IntoValues<K, V, A> {
2428 fn next_back(&mut self) -> Option<V> {
2429 self.inner.next_back().map(|(_, v)| v)
2430 }
2431}
2432
2433#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2434impl<K, V, A: Allocator + Clone> ExactSizeIterator for IntoValues<K, V, A> {
2435 fn len(&self) -> usize {
2436 self.inner.len()
2437 }
2438}
2439
2440#[unstable(feature = "trusted_len", issue = "37572")]
2441unsafe impl<K, V, A: Allocator + Clone> TrustedLen for IntoValues<K, V, A> {}
2442
2443#[stable(feature = "map_into_keys_values", since = "1.54.0")]
2444impl<K, V, A: Allocator + Clone> FusedIterator for IntoValues<K, V, A> {}
2445
2446#[stable(feature = "default_iters", since = "1.70.0")]
2447impl<K, V, A> Default for IntoValues<K, V, A>
2448where
2449 A: Allocator + Default + Clone,
2450{
2451 /// Creates an empty `btree_map::IntoValues`.
2452 ///
2453 /// ```
2454 /// # use std::collections::btree_map;
2455 /// let iter: btree_map::IntoValues<u8, u8> = Default::default();
2456 /// assert_eq!(iter.len(), 0);
2457 /// ```
2458 fn default() -> Self {
2459 IntoValues { inner: Default::default() }
2460 }
2461}
2462
2463#[stable(feature = "btree_range", since = "1.17.0")]
2464impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
2465 fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
2466 self.inner.next_back_checked()
2467 }
2468}
2469
2470#[stable(feature = "fused", since = "1.26.0")]
2471impl<K, V> FusedIterator for Range<'_, K, V> {}
2472
2473#[stable(feature = "btree_range", since = "1.17.0")]
2474impl<K, V> Clone for Range<'_, K, V> {
2475 fn clone(&self) -> Self {
2476 Range { inner: self.inner.clone() }
2477 }
2478}
2479
2480#[stable(feature = "btree_range", since = "1.17.0")]
2481impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
2482 type Item = (&'a K, &'a mut V);
2483
2484 fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
2485 self.inner.next_checked()
2486 }
2487
2488 fn last(mut self) -> Option<(&'a K, &'a mut V)> {
2489 self.next_back()
2490 }
2491
2492 fn min(mut self) -> Option<(&'a K, &'a mut V)>
2493 where
2494 (&'a K, &'a mut V): Ord,
2495 {
2496 self.next()
2497 }
2498
2499 fn max(mut self) -> Option<(&'a K, &'a mut V)>
2500 where
2501 (&'a K, &'a mut V): Ord,
2502 {
2503 self.next_back()
2504 }
2505}
2506
2507#[stable(feature = "btree_range", since = "1.17.0")]
2508impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
2509 fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
2510 self.inner.next_back_checked()
2511 }
2512}
2513
2514#[stable(feature = "fused", since = "1.26.0")]
2515impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
2516
2517#[stable(feature = "rust1", since = "1.0.0")]
2518impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
2519 /// Constructs a `BTreeMap<K, V>` from an iterator of key-value pairs.
2520 ///
2521 /// If the iterator produces any pairs with equal keys,
2522 /// all but one of the corresponding values will be dropped.
2523 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
2524 let mut inputs: Vec<_> = iter.into_iter().collect();
2525
2526 if inputs.is_empty() {
2527 return BTreeMap::new();
2528 }
2529
2530 // use stable sort to preserve the insertion order.
2531 inputs.sort_by(|a, b| a.0.cmp(&b.0));
2532 BTreeMap::bulk_build_from_sorted_iter(inputs, Global)
2533 }
2534}
2535
2536#[stable(feature = "rust1", since = "1.0.0")]
2537impl<K: Ord, V, A: Allocator + Clone> Extend<(K, V)> for BTreeMap<K, V, A> {
2538 #[inline]
2539 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
2540 iter.into_iter().for_each(move |(k, v)| {
2541 self.insert(k, v);
2542 });
2543 }
2544
2545 #[inline]
2546 fn extend_one(&mut self, (k, v): (K, V)) {
2547 self.insert(k, v);
2548 }
2549}
2550
2551#[stable(feature = "extend_ref", since = "1.2.0")]
2552impl<'a, K: Ord + Copy, V: Copy, A: Allocator + Clone> Extend<(&'a K, &'a V)>
2553 for BTreeMap<K, V, A>
2554{
2555 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
2556 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
2557 }
2558
2559 #[inline]
2560 fn extend_one(&mut self, (&k, &v): (&'a K, &'a V)) {
2561 self.insert(k, v);
2562 }
2563}
2564
2565#[stable(feature = "rust1", since = "1.0.0")]
2566impl<K: Hash, V: Hash, A: Allocator + Clone> Hash for BTreeMap<K, V, A> {
2567 fn hash<H: Hasher>(&self, state: &mut H) {
2568 state.write_length_prefix(self.len());
2569 for elt in self {
2570 elt.hash(state);
2571 }
2572 }
2573}
2574
2575#[stable(feature = "rust1", since = "1.0.0")]
2576impl<K, V> Default for BTreeMap<K, V> {
2577 /// Creates an empty `BTreeMap`.
2578 fn default() -> BTreeMap<K, V> {
2579 BTreeMap::new()
2580 }
2581}
2582
2583#[stable(feature = "rust1", since = "1.0.0")]
2584impl<K: PartialEq, V: PartialEq, A: Allocator + Clone> PartialEq for BTreeMap<K, V, A> {
2585 fn eq(&self, other: &BTreeMap<K, V, A>) -> bool {
2586 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
2587 }
2588}
2589
2590#[stable(feature = "rust1", since = "1.0.0")]
2591impl<K: Eq, V: Eq, A: Allocator + Clone> Eq for BTreeMap<K, V, A> {}
2592
2593#[stable(feature = "rust1", since = "1.0.0")]
2594impl<K: PartialOrd, V: PartialOrd, A: Allocator + Clone> PartialOrd for BTreeMap<K, V, A> {
2595 #[inline]
2596 fn partial_cmp(&self, other: &BTreeMap<K, V, A>) -> Option<Ordering> {
2597 self.iter().partial_cmp(other.iter())
2598 }
2599}
2600
2601#[stable(feature = "rust1", since = "1.0.0")]
2602impl<K: Ord, V: Ord, A: Allocator + Clone> Ord for BTreeMap<K, V, A> {
2603 #[inline]
2604 fn cmp(&self, other: &BTreeMap<K, V, A>) -> Ordering {
2605 self.iter().cmp(other.iter())
2606 }
2607}
2608
2609#[stable(feature = "rust1", since = "1.0.0")]
2610impl<K: Debug, V: Debug, A: Allocator + Clone> Debug for BTreeMap<K, V, A> {
2611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2612 f.debug_map().entries(self.iter()).finish()
2613 }
2614}
2615
2616#[stable(feature = "rust1", since = "1.0.0")]
2617impl<K, Q: ?Sized, V, A: Allocator + Clone> Index<&Q> for BTreeMap<K, V, A>
2618where
2619 K: Borrow<Q> + Ord,
2620 Q: Ord,
2621{
2622 type Output = V;
2623
2624 /// Returns a reference to the value corresponding to the supplied key.
2625 ///
2626 /// # Panics
2627 ///
2628 /// Panics if the key is not present in the `BTreeMap`.
2629 #[inline]
2630 fn index(&self, key: &Q) -> &V {
2631 self.get(key).expect("no entry found for key")
2632 }
2633}
2634
2635#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2636impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2637 /// Converts a `[(K, V); N]` into a `BTreeMap<K, V>`.
2638 ///
2639 /// If any entries in the array have equal keys,
2640 /// all but one of the corresponding values will be dropped.
2641 ///
2642 /// ```
2643 /// use std::collections::BTreeMap;
2644 ///
2645 /// let map1 = BTreeMap::from([(1, 2), (3, 4)]);
2646 /// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2647 /// assert_eq!(map1, map2);
2648 /// ```
2649 fn from(mut arr: [(K, V); N]) -> Self {
2650 if N == 0 {
2651 return BTreeMap::new();
2652 }
2653
2654 // use stable sort to preserve the insertion order.
2655 arr.sort_by(|a, b| a.0.cmp(&b.0));
2656 BTreeMap::bulk_build_from_sorted_iter(arr, Global)
2657 }
2658}
2659
2660impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
2661 /// Gets an iterator over the entries of the map, sorted by key.
2662 ///
2663 /// # Examples
2664 ///
2665 /// ```
2666 /// use std::collections::BTreeMap;
2667 ///
2668 /// let mut map = BTreeMap::new();
2669 /// map.insert(3, "c");
2670 /// map.insert(2, "b");
2671 /// map.insert(1, "a");
2672 ///
2673 /// for (key, value) in map.iter() {
2674 /// println!("{key}: {value}");
2675 /// }
2676 ///
2677 /// let (first_key, first_value) = map.iter().next().unwrap();
2678 /// assert_eq!((*first_key, *first_value), (1, "a"));
2679 /// ```
2680 #[stable(feature = "rust1", since = "1.0.0")]
2681 pub fn iter(&self) -> Iter<'_, K, V> {
2682 if let Some(root) = &self.root {
2683 let full_range = root.reborrow().full_range();
2684
2685 Iter { range: full_range, length: self.length }
2686 } else {
2687 Iter { range: LazyLeafRange::none(), length: 0 }
2688 }
2689 }
2690
2691 /// Gets a mutable iterator over the entries of the map, sorted by key.
2692 ///
2693 /// # Examples
2694 ///
2695 /// ```
2696 /// use std::collections::BTreeMap;
2697 ///
2698 /// let mut map = BTreeMap::from([
2699 /// ("a", 1),
2700 /// ("b", 2),
2701 /// ("c", 3),
2702 /// ]);
2703 ///
2704 /// // add 10 to the value if the key isn't "a"
2705 /// for (key, value) in map.iter_mut() {
2706 /// if key != &"a" {
2707 /// *value += 10;
2708 /// }
2709 /// }
2710 /// ```
2711 #[stable(feature = "rust1", since = "1.0.0")]
2712 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
2713 if let Some(root) = &mut self.root {
2714 let full_range = root.borrow_valmut().full_range();
2715
2716 IterMut { range: full_range, length: self.length, _marker: PhantomData }
2717 } else {
2718 IterMut { range: LazyLeafRange::none(), length: 0, _marker: PhantomData }
2719 }
2720 }
2721
2722 /// Gets an iterator over the keys of the map, in sorted order.
2723 ///
2724 /// # Examples
2725 ///
2726 /// ```
2727 /// use std::collections::BTreeMap;
2728 ///
2729 /// let mut a = BTreeMap::new();
2730 /// a.insert(2, "b");
2731 /// a.insert(1, "a");
2732 ///
2733 /// let keys: Vec<_> = a.keys().cloned().collect();
2734 /// assert_eq!(keys, [1, 2]);
2735 /// ```
2736 #[stable(feature = "rust1", since = "1.0.0")]
2737 pub fn keys(&self) -> Keys<'_, K, V> {
2738 Keys { inner: self.iter() }
2739 }
2740
2741 /// Gets an iterator over the values of the map, in order by key.
2742 ///
2743 /// # Examples
2744 ///
2745 /// ```
2746 /// use std::collections::BTreeMap;
2747 ///
2748 /// let mut a = BTreeMap::new();
2749 /// a.insert(1, "hello");
2750 /// a.insert(2, "goodbye");
2751 ///
2752 /// let values: Vec<&str> = a.values().cloned().collect();
2753 /// assert_eq!(values, ["hello", "goodbye"]);
2754 /// ```
2755 #[stable(feature = "rust1", since = "1.0.0")]
2756 pub fn values(&self) -> Values<'_, K, V> {
2757 Values { inner: self.iter() }
2758 }
2759
2760 /// Gets a mutable iterator over the values of the map, in order by key.
2761 ///
2762 /// # Examples
2763 ///
2764 /// ```
2765 /// use std::collections::BTreeMap;
2766 ///
2767 /// let mut a = BTreeMap::new();
2768 /// a.insert(1, String::from("hello"));
2769 /// a.insert(2, String::from("goodbye"));
2770 ///
2771 /// for value in a.values_mut() {
2772 /// value.push_str("!");
2773 /// }
2774 ///
2775 /// let values: Vec<String> = a.values().cloned().collect();
2776 /// assert_eq!(values, [String::from("hello!"),
2777 /// String::from("goodbye!")]);
2778 /// ```
2779 #[stable(feature = "map_values_mut", since = "1.10.0")]
2780 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
2781 ValuesMut { inner: self.iter_mut() }
2782 }
2783
2784 /// Returns the number of elements in the map.
2785 ///
2786 /// # Examples
2787 ///
2788 /// ```
2789 /// use std::collections::BTreeMap;
2790 ///
2791 /// let mut a = BTreeMap::new();
2792 /// assert_eq!(a.len(), 0);
2793 /// a.insert(1, "a");
2794 /// assert_eq!(a.len(), 1);
2795 /// ```
2796 #[must_use]
2797 #[stable(feature = "rust1", since = "1.0.0")]
2798 #[rustc_const_unstable(
2799 feature = "const_btree_len",
2800 issue = "71835",
2801 implied_by = "const_btree_new"
2802 )]
2803 #[rustc_confusables("length", "size")]
2804 pub const fn len(&self) -> usize {
2805 self.length
2806 }
2807
2808 /// Returns `true` if the map contains no elements.
2809 ///
2810 /// # Examples
2811 ///
2812 /// ```
2813 /// use std::collections::BTreeMap;
2814 ///
2815 /// let mut a = BTreeMap::new();
2816 /// assert!(a.is_empty());
2817 /// a.insert(1, "a");
2818 /// assert!(!a.is_empty());
2819 /// ```
2820 #[must_use]
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 #[rustc_const_unstable(
2823 feature = "const_btree_len",
2824 issue = "71835",
2825 implied_by = "const_btree_new"
2826 )]
2827 pub const fn is_empty(&self) -> bool {
2828 self.len() == 0
2829 }
2830
2831 /// Returns a [`Cursor`] pointing at the gap before the smallest key
2832 /// greater than the given bound.
2833 ///
2834 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2835 /// gap before the smallest key greater than or equal to `x`.
2836 ///
2837 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2838 /// gap before the smallest key greater than `x`.
2839 ///
2840 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2841 /// gap before the smallest key in the map.
2842 ///
2843 /// # Examples
2844 ///
2845 /// ```
2846 /// #![feature(btree_cursors)]
2847 ///
2848 /// use std::collections::BTreeMap;
2849 /// use std::ops::Bound;
2850 ///
2851 /// let map = BTreeMap::from([
2852 /// (1, "a"),
2853 /// (2, "b"),
2854 /// (3, "c"),
2855 /// (4, "d"),
2856 /// ]);
2857 ///
2858 /// let cursor = map.lower_bound(Bound::Included(&2));
2859 /// assert_eq!(cursor.peek_prev(), Some((&1, &"a")));
2860 /// assert_eq!(cursor.peek_next(), Some((&2, &"b")));
2861 ///
2862 /// let cursor = map.lower_bound(Bound::Excluded(&2));
2863 /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2864 /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2865 ///
2866 /// let cursor = map.lower_bound(Bound::Unbounded);
2867 /// assert_eq!(cursor.peek_prev(), None);
2868 /// assert_eq!(cursor.peek_next(), Some((&1, &"a")));
2869 /// ```
2870 #[unstable(feature = "btree_cursors", issue = "107540")]
2871 pub fn lower_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2872 where
2873 K: Borrow<Q> + Ord,
2874 Q: Ord,
2875 {
2876 let root_node = match self.root.as_ref() {
2877 None => return Cursor { current: None, root: None },
2878 Some(root) => root.reborrow(),
2879 };
2880 let edge = root_node.lower_bound(SearchBound::from_range(bound));
2881 Cursor { current: Some(edge), root: self.root.as_ref() }
2882 }
2883
2884 /// Returns a [`CursorMut`] pointing at the gap before the smallest key
2885 /// greater than the given bound.
2886 ///
2887 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2888 /// gap before the smallest key greater than or equal to `x`.
2889 ///
2890 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2891 /// gap before the smallest key greater than `x`.
2892 ///
2893 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2894 /// gap before the smallest key in the map.
2895 ///
2896 /// # Examples
2897 ///
2898 /// ```
2899 /// #![feature(btree_cursors)]
2900 ///
2901 /// use std::collections::BTreeMap;
2902 /// use std::ops::Bound;
2903 ///
2904 /// let mut map = BTreeMap::from([
2905 /// (1, "a"),
2906 /// (2, "b"),
2907 /// (3, "c"),
2908 /// (4, "d"),
2909 /// ]);
2910 ///
2911 /// let mut cursor = map.lower_bound_mut(Bound::Included(&2));
2912 /// assert_eq!(cursor.peek_prev(), Some((&1, &mut "a")));
2913 /// assert_eq!(cursor.peek_next(), Some((&2, &mut "b")));
2914 ///
2915 /// let mut cursor = map.lower_bound_mut(Bound::Excluded(&2));
2916 /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
2917 /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
2918 ///
2919 /// let mut cursor = map.lower_bound_mut(Bound::Unbounded);
2920 /// assert_eq!(cursor.peek_prev(), None);
2921 /// assert_eq!(cursor.peek_next(), Some((&1, &mut "a")));
2922 /// ```
2923 #[unstable(feature = "btree_cursors", issue = "107540")]
2924 pub fn lower_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
2925 where
2926 K: Borrow<Q> + Ord,
2927 Q: Ord,
2928 {
2929 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
2930 let root_node = match root.as_mut() {
2931 None => {
2932 return CursorMut {
2933 inner: CursorMutKey {
2934 current: None,
2935 root: dormant_root,
2936 length: &mut self.length,
2937 alloc: &mut *self.alloc,
2938 },
2939 };
2940 }
2941 Some(root) => root.borrow_mut(),
2942 };
2943 let edge = root_node.lower_bound(SearchBound::from_range(bound));
2944 CursorMut {
2945 inner: CursorMutKey {
2946 current: Some(edge),
2947 root: dormant_root,
2948 length: &mut self.length,
2949 alloc: &mut *self.alloc,
2950 },
2951 }
2952 }
2953
2954 /// Returns a [`Cursor`] pointing at the gap after the greatest key
2955 /// smaller than the given bound.
2956 ///
2957 /// Passing `Bound::Included(x)` will return a cursor pointing to the
2958 /// gap after the greatest key smaller than or equal to `x`.
2959 ///
2960 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
2961 /// gap after the greatest key smaller than `x`.
2962 ///
2963 /// Passing `Bound::Unbounded` will return a cursor pointing to the
2964 /// gap after the greatest key in the map.
2965 ///
2966 /// # Examples
2967 ///
2968 /// ```
2969 /// #![feature(btree_cursors)]
2970 ///
2971 /// use std::collections::BTreeMap;
2972 /// use std::ops::Bound;
2973 ///
2974 /// let map = BTreeMap::from([
2975 /// (1, "a"),
2976 /// (2, "b"),
2977 /// (3, "c"),
2978 /// (4, "d"),
2979 /// ]);
2980 ///
2981 /// let cursor = map.upper_bound(Bound::Included(&3));
2982 /// assert_eq!(cursor.peek_prev(), Some((&3, &"c")));
2983 /// assert_eq!(cursor.peek_next(), Some((&4, &"d")));
2984 ///
2985 /// let cursor = map.upper_bound(Bound::Excluded(&3));
2986 /// assert_eq!(cursor.peek_prev(), Some((&2, &"b")));
2987 /// assert_eq!(cursor.peek_next(), Some((&3, &"c")));
2988 ///
2989 /// let cursor = map.upper_bound(Bound::Unbounded);
2990 /// assert_eq!(cursor.peek_prev(), Some((&4, &"d")));
2991 /// assert_eq!(cursor.peek_next(), None);
2992 /// ```
2993 #[unstable(feature = "btree_cursors", issue = "107540")]
2994 pub fn upper_bound<Q: ?Sized>(&self, bound: Bound<&Q>) -> Cursor<'_, K, V>
2995 where
2996 K: Borrow<Q> + Ord,
2997 Q: Ord,
2998 {
2999 let root_node = match self.root.as_ref() {
3000 None => return Cursor { current: None, root: None },
3001 Some(root) => root.reborrow(),
3002 };
3003 let edge = root_node.upper_bound(SearchBound::from_range(bound));
3004 Cursor { current: Some(edge), root: self.root.as_ref() }
3005 }
3006
3007 /// Returns a [`CursorMut`] pointing at the gap after the greatest key
3008 /// smaller than the given bound.
3009 ///
3010 /// Passing `Bound::Included(x)` will return a cursor pointing to the
3011 /// gap after the greatest key smaller than or equal to `x`.
3012 ///
3013 /// Passing `Bound::Excluded(x)` will return a cursor pointing to the
3014 /// gap after the greatest key smaller than `x`.
3015 ///
3016 /// Passing `Bound::Unbounded` will return a cursor pointing to the
3017 /// gap after the greatest key in the map.
3018 ///
3019 /// # Examples
3020 ///
3021 /// ```
3022 /// #![feature(btree_cursors)]
3023 ///
3024 /// use std::collections::BTreeMap;
3025 /// use std::ops::Bound;
3026 ///
3027 /// let mut map = BTreeMap::from([
3028 /// (1, "a"),
3029 /// (2, "b"),
3030 /// (3, "c"),
3031 /// (4, "d"),
3032 /// ]);
3033 ///
3034 /// let mut cursor = map.upper_bound_mut(Bound::Included(&3));
3035 /// assert_eq!(cursor.peek_prev(), Some((&3, &mut "c")));
3036 /// assert_eq!(cursor.peek_next(), Some((&4, &mut "d")));
3037 ///
3038 /// let mut cursor = map.upper_bound_mut(Bound::Excluded(&3));
3039 /// assert_eq!(cursor.peek_prev(), Some((&2, &mut "b")));
3040 /// assert_eq!(cursor.peek_next(), Some((&3, &mut "c")));
3041 ///
3042 /// let mut cursor = map.upper_bound_mut(Bound::Unbounded);
3043 /// assert_eq!(cursor.peek_prev(), Some((&4, &mut "d")));
3044 /// assert_eq!(cursor.peek_next(), None);
3045 /// ```
3046 #[unstable(feature = "btree_cursors", issue = "107540")]
3047 pub fn upper_bound_mut<Q: ?Sized>(&mut self, bound: Bound<&Q>) -> CursorMut<'_, K, V, A>
3048 where
3049 K: Borrow<Q> + Ord,
3050 Q: Ord,
3051 {
3052 let (root, dormant_root) = DormantMutRef::new(&mut self.root);
3053 let root_node = match root.as_mut() {
3054 None => {
3055 return CursorMut {
3056 inner: CursorMutKey {
3057 current: None,
3058 root: dormant_root,
3059 length: &mut self.length,
3060 alloc: &mut *self.alloc,
3061 },
3062 };
3063 }
3064 Some(root) => root.borrow_mut(),
3065 };
3066 let edge = root_node.upper_bound(SearchBound::from_range(bound));
3067 CursorMut {
3068 inner: CursorMutKey {
3069 current: Some(edge),
3070 root: dormant_root,
3071 length: &mut self.length,
3072 alloc: &mut *self.alloc,
3073 },
3074 }
3075 }
3076}
3077
3078/// A cursor over a `BTreeMap`.
3079///
3080/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
3081///
3082/// Cursors always point to a gap between two elements in the map, and can
3083/// operate on the two immediately adjacent elements.
3084///
3085/// A `Cursor` is created with the [`BTreeMap::lower_bound`] and [`BTreeMap::upper_bound`] methods.
3086#[unstable(feature = "btree_cursors", issue = "107540")]
3087pub struct Cursor<'a, K: 'a, V: 'a> {
3088 // If current is None then it means the tree has not been allocated yet.
3089 current: Option<Handle<NodeRef<marker::Immut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3090 root: Option<&'a node::Root<K, V>>,
3091}
3092
3093#[unstable(feature = "btree_cursors", issue = "107540")]
3094impl<K, V> Clone for Cursor<'_, K, V> {
3095 fn clone(&self) -> Self {
3096 let Cursor { current, root } = *self;
3097 Cursor { current, root }
3098 }
3099}
3100
3101#[unstable(feature = "btree_cursors", issue = "107540")]
3102impl<K: Debug, V: Debug> Debug for Cursor<'_, K, V> {
3103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3104 f.write_str("Cursor")
3105 }
3106}
3107
3108/// A cursor over a `BTreeMap` with editing operations.
3109///
3110/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3111/// safely mutate the map during iteration. This is because the lifetime of its yielded
3112/// references is tied to its own lifetime, instead of just the underlying map. This means
3113/// cursors cannot yield multiple elements at once.
3114///
3115/// Cursors always point to a gap between two elements in the map, and can
3116/// operate on the two immediately adjacent elements.
3117///
3118/// A `CursorMut` is created with the [`BTreeMap::lower_bound_mut`] and [`BTreeMap::upper_bound_mut`]
3119/// methods.
3120#[unstable(feature = "btree_cursors", issue = "107540")]
3121pub struct CursorMut<
3122 'a,
3123 K: 'a,
3124 V: 'a,
3125 #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3126> {
3127 inner: CursorMutKey<'a, K, V, A>,
3128}
3129
3130#[unstable(feature = "btree_cursors", issue = "107540")]
3131impl<K: Debug, V: Debug, A> Debug for CursorMut<'_, K, V, A> {
3132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133 f.write_str("CursorMut")
3134 }
3135}
3136
3137/// A cursor over a `BTreeMap` with editing operations, and which allows
3138/// mutating the key of elements.
3139///
3140/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
3141/// safely mutate the map during iteration. This is because the lifetime of its yielded
3142/// references is tied to its own lifetime, instead of just the underlying map. This means
3143/// cursors cannot yield multiple elements at once.
3144///
3145/// Cursors always point to a gap between two elements in the map, and can
3146/// operate on the two immediately adjacent elements.
3147///
3148/// A `CursorMutKey` is created from a [`CursorMut`] with the
3149/// [`CursorMut::with_mutable_key`] method.
3150///
3151/// # Safety
3152///
3153/// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3154/// invariants are maintained. Specifically:
3155///
3156/// * The key of the newly inserted element must be unique in the tree.
3157/// * All keys in the tree must remain in sorted order.
3158#[unstable(feature = "btree_cursors", issue = "107540")]
3159pub struct CursorMutKey<
3160 'a,
3161 K: 'a,
3162 V: 'a,
3163 #[unstable(feature = "allocator_api", issue = "32838")] A = Global,
3164> {
3165 // If current is None then it means the tree has not been allocated yet.
3166 current: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
3167 root: DormantMutRef<'a, Option<node::Root<K, V>>>,
3168 length: &'a mut usize,
3169 alloc: &'a mut A,
3170}
3171
3172#[unstable(feature = "btree_cursors", issue = "107540")]
3173impl<K: Debug, V: Debug, A> Debug for CursorMutKey<'_, K, V, A> {
3174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3175 f.write_str("CursorMutKey")
3176 }
3177}
3178
3179impl<'a, K, V> Cursor<'a, K, V> {
3180 /// Advances the cursor to the next gap, returning the key and value of the
3181 /// element that it moved over.
3182 ///
3183 /// If the cursor is already at the end of the map then `None` is returned
3184 /// and the cursor is not moved.
3185 #[unstable(feature = "btree_cursors", issue = "107540")]
3186 pub fn next(&mut self) -> Option<(&'a K, &'a V)> {
3187 let current = self.current.take()?;
3188 match current.next_kv() {
3189 Ok(kv) => {
3190 let result = kv.into_kv();
3191 self.current = Some(kv.next_leaf_edge());
3192 Some(result)
3193 }
3194 Err(root) => {
3195 self.current = Some(root.last_leaf_edge());
3196 None
3197 }
3198 }
3199 }
3200
3201 /// Advances the cursor to the previous gap, returning the key and value of
3202 /// the element that it moved over.
3203 ///
3204 /// If the cursor is already at the start of the map then `None` is returned
3205 /// and the cursor is not moved.
3206 #[unstable(feature = "btree_cursors", issue = "107540")]
3207 pub fn prev(&mut self) -> Option<(&'a K, &'a V)> {
3208 let current = self.current.take()?;
3209 match current.next_back_kv() {
3210 Ok(kv) => {
3211 let result = kv.into_kv();
3212 self.current = Some(kv.next_back_leaf_edge());
3213 Some(result)
3214 }
3215 Err(root) => {
3216 self.current = Some(root.first_leaf_edge());
3217 None
3218 }
3219 }
3220 }
3221
3222 /// Returns a reference to the key and value of the next element without
3223 /// moving the cursor.
3224 ///
3225 /// If the cursor is at the end of the map then `None` is returned.
3226 #[unstable(feature = "btree_cursors", issue = "107540")]
3227 pub fn peek_next(&self) -> Option<(&'a K, &'a V)> {
3228 self.clone().next()
3229 }
3230
3231 /// Returns a reference to the key and value of the previous element
3232 /// without moving the cursor.
3233 ///
3234 /// If the cursor is at the start of the map then `None` is returned.
3235 #[unstable(feature = "btree_cursors", issue = "107540")]
3236 pub fn peek_prev(&self) -> Option<(&'a K, &'a V)> {
3237 self.clone().prev()
3238 }
3239}
3240
3241impl<'a, K, V, A> CursorMut<'a, K, V, A> {
3242 /// Advances the cursor to the next gap, returning the key and value of the
3243 /// element that it moved over.
3244 ///
3245 /// If the cursor is already at the end of the map then `None` is returned
3246 /// and the cursor is not moved.
3247 #[unstable(feature = "btree_cursors", issue = "107540")]
3248 pub fn next(&mut self) -> Option<(&K, &mut V)> {
3249 let (k, v) = self.inner.next()?;
3250 Some((&*k, v))
3251 }
3252
3253 /// Advances the cursor to the previous gap, returning the key and value of
3254 /// the element that it moved over.
3255 ///
3256 /// If the cursor is already at the start of the map then `None` is returned
3257 /// and the cursor is not moved.
3258 #[unstable(feature = "btree_cursors", issue = "107540")]
3259 pub fn prev(&mut self) -> Option<(&K, &mut V)> {
3260 let (k, v) = self.inner.prev()?;
3261 Some((&*k, v))
3262 }
3263
3264 /// Returns a reference to the key and value of the next element without
3265 /// moving the cursor.
3266 ///
3267 /// If the cursor is at the end of the map then `None` is returned.
3268 #[unstable(feature = "btree_cursors", issue = "107540")]
3269 pub fn peek_next(&mut self) -> Option<(&K, &mut V)> {
3270 let (k, v) = self.inner.peek_next()?;
3271 Some((&*k, v))
3272 }
3273
3274 /// Returns a reference to the key and value of the previous element
3275 /// without moving the cursor.
3276 ///
3277 /// If the cursor is at the start of the map then `None` is returned.
3278 #[unstable(feature = "btree_cursors", issue = "107540")]
3279 pub fn peek_prev(&mut self) -> Option<(&K, &mut V)> {
3280 let (k, v) = self.inner.peek_prev()?;
3281 Some((&*k, v))
3282 }
3283
3284 /// Returns a read-only cursor pointing to the same location as the
3285 /// `CursorMut`.
3286 ///
3287 /// The lifetime of the returned `Cursor` is bound to that of the
3288 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
3289 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
3290 #[unstable(feature = "btree_cursors", issue = "107540")]
3291 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3292 self.inner.as_cursor()
3293 }
3294
3295 /// Converts the cursor into a [`CursorMutKey`], which allows mutating
3296 /// the key of elements in the tree.
3297 ///
3298 /// # Safety
3299 ///
3300 /// Since this cursor allows mutating keys, you must ensure that the `BTreeMap`
3301 /// invariants are maintained. Specifically:
3302 ///
3303 /// * The key of the newly inserted element must be unique in the tree.
3304 /// * All keys in the tree must remain in sorted order.
3305 #[unstable(feature = "btree_cursors", issue = "107540")]
3306 pub unsafe fn with_mutable_key(self) -> CursorMutKey<'a, K, V, A> {
3307 self.inner
3308 }
3309}
3310
3311impl<'a, K, V, A> CursorMutKey<'a, K, V, A> {
3312 /// Advances the cursor to the next gap, returning the key and value of the
3313 /// element that it moved over.
3314 ///
3315 /// If the cursor is already at the end of the map then `None` is returned
3316 /// and the cursor is not moved.
3317 #[unstable(feature = "btree_cursors", issue = "107540")]
3318 pub fn next(&mut self) -> Option<(&mut K, &mut V)> {
3319 let current = self.current.take()?;
3320 match current.next_kv() {
3321 Ok(mut kv) => {
3322 // SAFETY: The key/value pointers remain valid even after the
3323 // cursor is moved forward. The lifetimes then prevent any
3324 // further access to the cursor.
3325 let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3326 let (k, v) = (k as *mut _, v as *mut _);
3327 self.current = Some(kv.next_leaf_edge());
3328 Some(unsafe { (&mut *k, &mut *v) })
3329 }
3330 Err(root) => {
3331 self.current = Some(root.last_leaf_edge());
3332 None
3333 }
3334 }
3335 }
3336
3337 /// Advances the cursor to the previous gap, returning the key and value of
3338 /// the element that it moved over.
3339 ///
3340 /// If the cursor is already at the start of the map then `None` is returned
3341 /// and the cursor is not moved.
3342 #[unstable(feature = "btree_cursors", issue = "107540")]
3343 pub fn prev(&mut self) -> Option<(&mut K, &mut V)> {
3344 let current = self.current.take()?;
3345 match current.next_back_kv() {
3346 Ok(mut kv) => {
3347 // SAFETY: The key/value pointers remain valid even after the
3348 // cursor is moved forward. The lifetimes then prevent any
3349 // further access to the cursor.
3350 let (k, v) = unsafe { kv.reborrow_mut().into_kv_mut() };
3351 let (k, v) = (k as *mut _, v as *mut _);
3352 self.current = Some(kv.next_back_leaf_edge());
3353 Some(unsafe { (&mut *k, &mut *v) })
3354 }
3355 Err(root) => {
3356 self.current = Some(root.first_leaf_edge());
3357 None
3358 }
3359 }
3360 }
3361
3362 /// Returns a reference to the key and value of the next element without
3363 /// moving the cursor.
3364 ///
3365 /// If the cursor is at the end of the map then `None` is returned.
3366 #[unstable(feature = "btree_cursors", issue = "107540")]
3367 pub fn peek_next(&mut self) -> Option<(&mut K, &mut V)> {
3368 let current = self.current.as_mut()?;
3369 // SAFETY: We're not using this to mutate the tree.
3370 let kv = unsafe { current.reborrow_mut() }.next_kv().ok()?.into_kv_mut();
3371 Some(kv)
3372 }
3373
3374 /// Returns a reference to the key and value of the previous element
3375 /// without moving the cursor.
3376 ///
3377 /// If the cursor is at the start of the map then `None` is returned.
3378 #[unstable(feature = "btree_cursors", issue = "107540")]
3379 pub fn peek_prev(&mut self) -> Option<(&mut K, &mut V)> {
3380 let current = self.current.as_mut()?;
3381 // SAFETY: We're not using this to mutate the tree.
3382 let kv = unsafe { current.reborrow_mut() }.next_back_kv().ok()?.into_kv_mut();
3383 Some(kv)
3384 }
3385
3386 /// Returns a read-only cursor pointing to the same location as the
3387 /// `CursorMutKey`.
3388 ///
3389 /// The lifetime of the returned `Cursor` is bound to that of the
3390 /// `CursorMutKey`, which means it cannot outlive the `CursorMutKey` and that the
3391 /// `CursorMutKey` is frozen for the lifetime of the `Cursor`.
3392 #[unstable(feature = "btree_cursors", issue = "107540")]
3393 pub fn as_cursor(&self) -> Cursor<'_, K, V> {
3394 Cursor {
3395 // SAFETY: The tree is immutable while the cursor exists.
3396 root: unsafe { self.root.reborrow_shared().as_ref() },
3397 current: self.current.as_ref().map(|current| current.reborrow()),
3398 }
3399 }
3400}
3401
3402// Now the tree editing operations
3403impl<'a, K: Ord, V, A: Allocator + Clone> CursorMutKey<'a, K, V, A> {
3404 /// Inserts a new key-value pair into the map in the gap that the
3405 /// cursor is currently pointing to.
3406 ///
3407 /// After the insertion the cursor will be pointing at the gap before the
3408 /// newly inserted element.
3409 ///
3410 /// # Safety
3411 ///
3412 /// You must ensure that the `BTreeMap` invariants are maintained.
3413 /// Specifically:
3414 ///
3415 /// * The key of the newly inserted element must be unique in the tree.
3416 /// * All keys in the tree must remain in sorted order.
3417 #[unstable(feature = "btree_cursors", issue = "107540")]
3418 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3419 let edge = match self.current.take() {
3420 None => {
3421 // Tree is empty, allocate a new root.
3422 // SAFETY: We have no other reference to the tree.
3423 let root = unsafe { self.root.reborrow() };
3424 debug_assert!(root.is_none());
3425 let mut node = NodeRef::new_leaf(self.alloc.clone());
3426 // SAFETY: We don't touch the root while the handle is alive.
3427 let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3428 *root = Some(node.forget_type());
3429 *self.length += 1;
3430 self.current = Some(handle.left_edge());
3431 return;
3432 }
3433 Some(current) => current,
3434 };
3435
3436 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3437 drop(ins.left);
3438 // SAFETY: The handle to the newly inserted value is always on a
3439 // leaf node, so adding a new root node doesn't invalidate it.
3440 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3441 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3442 });
3443 self.current = Some(handle.left_edge());
3444 *self.length += 1;
3445 }
3446
3447 /// Inserts a new key-value pair into the map in the gap that the
3448 /// cursor is currently pointing to.
3449 ///
3450 /// After the insertion the cursor will be pointing at the gap after the
3451 /// newly inserted element.
3452 ///
3453 /// # Safety
3454 ///
3455 /// You must ensure that the `BTreeMap` invariants are maintained.
3456 /// Specifically:
3457 ///
3458 /// * The key of the newly inserted element must be unique in the tree.
3459 /// * All keys in the tree must remain in sorted order.
3460 #[unstable(feature = "btree_cursors", issue = "107540")]
3461 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3462 let edge = match self.current.take() {
3463 None => {
3464 // SAFETY: We have no other reference to the tree.
3465 match unsafe { self.root.reborrow() } {
3466 root @ None => {
3467 // Tree is empty, allocate a new root.
3468 let mut node = NodeRef::new_leaf(self.alloc.clone());
3469 // SAFETY: We don't touch the root while the handle is alive.
3470 let handle = unsafe { node.borrow_mut().push_with_handle(key, value) };
3471 *root = Some(node.forget_type());
3472 *self.length += 1;
3473 self.current = Some(handle.right_edge());
3474 return;
3475 }
3476 Some(root) => root.borrow_mut().last_leaf_edge(),
3477 }
3478 }
3479 Some(current) => current,
3480 };
3481
3482 let handle = edge.insert_recursing(key, value, self.alloc.clone(), |ins| {
3483 drop(ins.left);
3484 // SAFETY: The handle to the newly inserted value is always on a
3485 // leaf node, so adding a new root node doesn't invalidate it.
3486 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3487 root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
3488 });
3489 self.current = Some(handle.right_edge());
3490 *self.length += 1;
3491 }
3492
3493 /// Inserts a new key-value pair into the map in the gap that the
3494 /// cursor is currently pointing to.
3495 ///
3496 /// After the insertion the cursor will be pointing at the gap before the
3497 /// newly inserted element.
3498 ///
3499 /// If the inserted key is not greater than the key before the cursor
3500 /// (if any), or if it not less than the key after the cursor (if any),
3501 /// then an [`UnorderedKeyError`] is returned since this would
3502 /// invalidate the [`Ord`] invariant between the keys of the map.
3503 #[unstable(feature = "btree_cursors", issue = "107540")]
3504 pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3505 if let Some((prev, _)) = self.peek_prev() {
3506 if &key <= prev {
3507 return Err(UnorderedKeyError {});
3508 }
3509 }
3510 if let Some((next, _)) = self.peek_next() {
3511 if &key >= next {
3512 return Err(UnorderedKeyError {});
3513 }
3514 }
3515 unsafe {
3516 self.insert_after_unchecked(key, value);
3517 }
3518 Ok(())
3519 }
3520
3521 /// Inserts a new key-value pair into the map in the gap that the
3522 /// cursor is currently pointing to.
3523 ///
3524 /// After the insertion the cursor will be pointing at the gap after the
3525 /// newly inserted element.
3526 ///
3527 /// If the inserted key is not greater than the key before the cursor
3528 /// (if any), or if it not less than the key after the cursor (if any),
3529 /// then an [`UnorderedKeyError`] is returned since this would
3530 /// invalidate the [`Ord`] invariant between the keys of the map.
3531 #[unstable(feature = "btree_cursors", issue = "107540")]
3532 pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3533 if let Some((prev, _)) = self.peek_prev() {
3534 if &key <= prev {
3535 return Err(UnorderedKeyError {});
3536 }
3537 }
3538 if let Some((next, _)) = self.peek_next() {
3539 if &key >= next {
3540 return Err(UnorderedKeyError {});
3541 }
3542 }
3543 unsafe {
3544 self.insert_before_unchecked(key, value);
3545 }
3546 Ok(())
3547 }
3548
3549 /// Removes the next element from the `BTreeMap`.
3550 ///
3551 /// The element that was removed is returned. The cursor position is
3552 /// unchanged (before the removed element).
3553 #[unstable(feature = "btree_cursors", issue = "107540")]
3554 pub fn remove_next(&mut self) -> Option<(K, V)> {
3555 let current = self.current.take()?;
3556 if current.reborrow().next_kv().is_err() {
3557 self.current = Some(current);
3558 return None;
3559 }
3560 let mut emptied_internal_root = false;
3561 let (kv, pos) = current
3562 .next_kv()
3563 // This should be unwrap(), but that doesn't work because NodeRef
3564 // doesn't implement Debug. The condition is checked above.
3565 .ok()?
3566 .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3567 self.current = Some(pos);
3568 *self.length -= 1;
3569 if emptied_internal_root {
3570 // SAFETY: This is safe since current does not point within the now
3571 // empty root node.
3572 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3573 root.pop_internal_level(self.alloc.clone());
3574 }
3575 Some(kv)
3576 }
3577
3578 /// Removes the preceding element from the `BTreeMap`.
3579 ///
3580 /// The element that was removed is returned. The cursor position is
3581 /// unchanged (after the removed element).
3582 #[unstable(feature = "btree_cursors", issue = "107540")]
3583 pub fn remove_prev(&mut self) -> Option<(K, V)> {
3584 let current = self.current.take()?;
3585 if current.reborrow().next_back_kv().is_err() {
3586 self.current = Some(current);
3587 return None;
3588 }
3589 let mut emptied_internal_root = false;
3590 let (kv, pos) = current
3591 .next_back_kv()
3592 // This should be unwrap(), but that doesn't work because NodeRef
3593 // doesn't implement Debug. The condition is checked above.
3594 .ok()?
3595 .remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
3596 self.current = Some(pos);
3597 *self.length -= 1;
3598 if emptied_internal_root {
3599 // SAFETY: This is safe since current does not point within the now
3600 // empty root node.
3601 let root = unsafe { self.root.reborrow().as_mut().unwrap() };
3602 root.pop_internal_level(self.alloc.clone());
3603 }
3604 Some(kv)
3605 }
3606}
3607
3608impl<'a, K: Ord, V, A: Allocator + Clone> CursorMut<'a, K, V, A> {
3609 /// Inserts a new key-value pair into the map in the gap that the
3610 /// cursor is currently pointing to.
3611 ///
3612 /// After the insertion the cursor will be pointing at the gap after the
3613 /// newly inserted element.
3614 ///
3615 /// # Safety
3616 ///
3617 /// You must ensure that the `BTreeMap` invariants are maintained.
3618 /// Specifically:
3619 ///
3620 /// * The key of the newly inserted element must be unique in the tree.
3621 /// * All keys in the tree must remain in sorted order.
3622 #[unstable(feature = "btree_cursors", issue = "107540")]
3623 pub unsafe fn insert_after_unchecked(&mut self, key: K, value: V) {
3624 unsafe { self.inner.insert_after_unchecked(key, value) }
3625 }
3626
3627 /// Inserts a new key-value pair into the map in the gap that the
3628 /// cursor is currently pointing to.
3629 ///
3630 /// After the insertion the cursor will be pointing at the gap after the
3631 /// newly inserted element.
3632 ///
3633 /// # Safety
3634 ///
3635 /// You must ensure that the `BTreeMap` invariants are maintained.
3636 /// Specifically:
3637 ///
3638 /// * The key of the newly inserted element must be unique in the tree.
3639 /// * All keys in the tree must remain in sorted order.
3640 #[unstable(feature = "btree_cursors", issue = "107540")]
3641 pub unsafe fn insert_before_unchecked(&mut self, key: K, value: V) {
3642 unsafe { self.inner.insert_before_unchecked(key, value) }
3643 }
3644
3645 /// Inserts a new key-value pair into the map in the gap that the
3646 /// cursor is currently pointing to.
3647 ///
3648 /// After the insertion the cursor will be pointing at the gap before the
3649 /// newly inserted element.
3650 ///
3651 /// If the inserted key is not greater than the key before the cursor
3652 /// (if any), or if it not less than the key after the cursor (if any),
3653 /// then an [`UnorderedKeyError`] is returned since this would
3654 /// invalidate the [`Ord`] invariant between the keys of the map.
3655 #[unstable(feature = "btree_cursors", issue = "107540")]
3656 pub fn insert_after(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3657 self.inner.insert_after(key, value)
3658 }
3659
3660 /// Inserts a new key-value pair into the map in the gap that the
3661 /// cursor is currently pointing to.
3662 ///
3663 /// After the insertion the cursor will be pointing at the gap after the
3664 /// newly inserted element.
3665 ///
3666 /// If the inserted key is not greater than the key before the cursor
3667 /// (if any), or if it not less than the key after the cursor (if any),
3668 /// then an [`UnorderedKeyError`] is returned since this would
3669 /// invalidate the [`Ord`] invariant between the keys of the map.
3670 #[unstable(feature = "btree_cursors", issue = "107540")]
3671 pub fn insert_before(&mut self, key: K, value: V) -> Result<(), UnorderedKeyError> {
3672 self.inner.insert_before(key, value)
3673 }
3674
3675 /// Removes the next element from the `BTreeMap`.
3676 ///
3677 /// The element that was removed is returned. The cursor position is
3678 /// unchanged (before the removed element).
3679 #[unstable(feature = "btree_cursors", issue = "107540")]
3680 pub fn remove_next(&mut self) -> Option<(K, V)> {
3681 self.inner.remove_next()
3682 }
3683
3684 /// Removes the preceding element from the `BTreeMap`.
3685 ///
3686 /// The element that was removed is returned. The cursor position is
3687 /// unchanged (after the removed element).
3688 #[unstable(feature = "btree_cursors", issue = "107540")]
3689 pub fn remove_prev(&mut self) -> Option<(K, V)> {
3690 self.inner.remove_prev()
3691 }
3692}
3693
3694/// Error type returned by [`CursorMut::insert_before`] and
3695/// [`CursorMut::insert_after`] if the key being inserted is not properly
3696/// ordered with regards to adjacent keys.
3697#[derive(Clone, PartialEq, Eq, Debug)]
3698#[unstable(feature = "btree_cursors", issue = "107540")]
3699pub struct UnorderedKeyError {}
3700
3701#[unstable(feature = "btree_cursors", issue = "107540")]
3702impl fmt::Display for UnorderedKeyError {
3703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3704 write!(f, "key is not properly ordered relative to neighbors")
3705 }
3706}
3707
3708#[unstable(feature = "btree_cursors", issue = "107540")]
3709impl Error for UnorderedKeyError {}
3710
3711#[cfg(test)]
3712mod tests;